Vous êtes sur la page 1sur 13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

Week 14: C# 2008 Language Features


Topics 1. Understanding Implicitly Typed Local Variables 2. Understanding Automatic Properties 3. Understanding Extension Methods 4. Understanding Partial Methods 5. Understanding Object Initializer Syntax 6. Understanding Anonymous Types

I: Use Implicitly Typed Local Variables


We can use the inferred type to declare any local variable as var and the type will be inferred by the compiler from the expression on the right side of the initialization statement. This inferred type could be:

Built-in type Anonymous type (will be discussed later) User-defined type Type defined in the .NET Framework class library

Restrictions when using implicitly-typed variables:


can only be used when you are to declare and initialize the local variable in the same statement. The variable cannot be initialized to null. var cannot be used on fields at class scope. Variables declared by using var cannot be used in the initialization expression. In other words, var i = i++; produces a compile-time error. Multiple implicitly-typed variables cannot be initialized in the same statement. If a type named var is in scope, then you will get a compile-time error if you try to initialize a local variable with the var keyword.
var

Use Implicitly Typed Local Variables


how to use the var keyword in a common scenario in this scenario o not only the query variable o the iteration variable in the foreach statement must be implicitly typed by using var

1/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

Use Implicitly Typed Arrays


Implicitly-typed arrays are usually used in query expressions together with anonymous types and object and collection initializers

Exercise 1
private static void QueryNames(char firstLetter) { // Create the query. var is required because // the query produces a sequence of anonymous types. var studentQuery = from student in students where student.FirstName[0] == firstLetter select new { student.FirstName, student.LastName }; // Execute the query. foreach (var student in studentQuery) { Console.WriteLine("First = {0}, Last = {1}", student.FirstName, student.LastName); } }

1.1 Can define a nullable implicitly typed local variable? a.True b.False

1.2 List all variables in this program

1.3 Why does to Create the query. Var?

Exercise 2
// Error! Must assign a value! var myData; // Error! Must assign value at exact time of declaration! var myInt; myInt = 0; // Error! Can't assign null as initial value! var myObj = null;

2/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

2.1 From this program, when compiled, there are some errors. Why?

Exercise 3
var d = new[ ] { 1, "one", 2, "two", false }; Whats erros? Error mixed types

Exercise 4

4.1

class ThisWillNeverCompile { // Error! var cannot be used as field data! private var myInt = 10; // Error! var cannot be used as a return value or parameter type! public var MyMethod(var x, var y) { } }
List all variables in this program

4.2 Whats error?

3/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

II: Automatic Properties


To define an automatic property, it must support both read and write functionality.

Question :
1. Can Auto-implemented Properties improve the performace?(no) 2. How can I make read-only or write-only auto-implemented properties? (You can make the accessor as private) 3. Why Auto-Implemented Properties?

Exercise 1
// Read-only property? Error! public int MyReadOnlyProp { get; } // Write only property? Error! public int MyWriteOnlyProp { set; } Whats erros?

Exercise 2
static void Main(string[ ] args) { ... Garage g = new Garage(); // OK, prints default value of zero. Console.WriteLine("Number of Cars: {0}", g.NumberOfCars); // Runtime error! Backing field is currently null! Console.WriteLine(g.MyAuto.PetName); Console.ReadLine();

1.1.Whats erros?

Exercise 3
static void Main(string[ ] args) { ...

4/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

c.PetName = "Frank"; // Getting the value is still OK. Console.WriteLine("Your car is named {0}? That's odd...",c.PetName); Console.ReadLine(); } 3.1.Whats erros? ( // Error! Setting the PetName is only possible // from within the Car type or by a child type! )

5/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

III: Extension Methods


Extension methods are static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods Using extension methods: can add functionality to precompiled types an call an extension method on null base object dont have direct access to the members of the type they are extending

Exercise 1:
// Here is our only using directive. using System; namespace MyNewApp { class JustATest { void SomeMethod() { int i = 0; i.Foo(); } } }
3.1 Compile this program. Explain why this program cannot run?

3.2 Correct this program. Explain its output.

// Error! Need to import MyExtensionMethods namespace to extend int with Foo()!

Exercise 2:
static class MyExtensions { // This method allows any object to display the assembly it is defined in. public static void DisplayDefiningAssembly(this object obj) { Console.WriteLine("{0} lives here:\n\t->{1}\n", obj.GetType().Name, Assembly.GetAssembly(obj.GetType())); } public static int ReverseDigits(this int i) { char[ ] digits = i.ToString().ToCharArray();

6/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

Array.Reverse(digits); // Put back into string. string newDigits = new string(digits); // return the modified string back as an int.return int.Parse(newDigits); } }
2.1 What is written by this program?

2.2 List all variables in this program.

2.3 Can we use a string called

ReverseDigits()?

char[ ] digits = i.ToString().ToCharArray() explain?( // Translate int into a string, and then get all the characters.) Input =124; output=?
2.4

Exercise 3:
public static class CarExtensions { public static int SlowDown(this Car c) { return --Speed; } }

7/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

2.1 N

can we direct access to the members of Car ?

2.2 Whats error?.

// Error! This method is not deriving from Car!

2.3 What is proplem?

//Speed does not exist in this context!

2.2 how to Correct error.?

//return --c.Speed;

8/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

IV: Partial Methods


Allows to prototype a method in one file, yet implement it in another file

restrictions:
Partial methods can only be defined within a partial class. Partial methods must return void. Partial methods can be static or instance level. Partial methods can have arguments (including parameters modified by this, ref, or paramsbut not with the out modifier). Partial methods are always implicitly private.

Question: partials methods :


1. Must be declared inside a partial class. Y 2. Must be declared as a void return type. Y 3. Must be declared with the partial. Y 4. Can be marked as extern. N 5. Can be marked static or unsafe. Y 6. Cant be generic. N 7. Can have ref but not out parameters. Y 8. Cannot be referenced as a delegate until they are implemented Y 9. Can have access modifiers such as public, private or internal. N 10. Can be declared as virtual. N 11. Whats code-generation tool declares a partial method ?

9/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

V: Object Initializer Syntax


Ease construction and initialization of objects
can create a new type variable and assign a slew of properties and/or public fields in a few lines of code. Each member in the initialization list maps to the name of a public field or public property of the object being initialized.

Question:
1. Collections can contain many values? Y

Exercise 1:
using System; { class MainClass { static void Main() { double price, money; int n; double leftover; Console.Write("Enter candy price: "); price = Console.ReadLine(); Console.Write("Enter number of candies: "); n = Console.ReadLine(); Console.Write("Enter your money :"); money = Console.ReadLine(); leftover = money - price * n; Console.WriteLine("You have {0} bahts left.", leftover); Console.ReadLine(); } } }
1.1 Compile this program. Explain why this program cannot run?

1.2 Correct this program. Explain its output.

10/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

Exercise 2:
1. Point finalPoint = new Point { X = 30, Y = 30 }; 2. Point finalPoint = new Point() { X = 30, Y = 30 };
2.1

compare 2 constructor above?

2.2 which is implicity?.

11/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

VI: Anonymous Types


method code is specified in-place does not require the declaration of a named method anonymous method can access Foo's local variable sum return terminates the anonymous method (not the enclosing method)

Restrictions
must not have formal parameters of the kind params T[] must not be assigned to object must not access ref or out parameters of the enclosing method

Question: 1. Anonymous Methods does not require the declaration of a named method? Y Exercise 1:
static void Main(string[ ] args) { Console.WriteLine("***** Fun with Anonymous types *****\n"); // Make an anonymous type representing a car. var myCar = new {Color = "Bright Pink", Make = "Saab", CurrentSpeed = 55}; // Reflect over what the compiler generated. ReflectOverAnonymousType(myCar); Console.ReadLine(); } 1.1 Is the myCar object is of type <>f__AnonymousType0`3 ?

1.2 .Is the assigned type name access directly to C# code base?

Exercise 2:
Make an anonymous type that is composed of another? var purchaseItem = new { TimeBought = DateTime.Now, ItemBought = new {Color = "Red", Make = "Saab", CurrentSpeed = 55}, Price = 34.000}; ReflectOverAnonymousType(purchaseItem);

Exercise 3:
Console.WriteLine("Same anonymous object!"); // Are they considered equal when using ==? 12/13

HaNoi University of Technology

Week 14: C# 2008 Language Features Mastering C# 2008

if (firstCar == secondCar) Console.WriteLine("Same anonymous object!"); else Console.WriteLine("Not the same anonymous object!"); // Are these objects the same underlying type? if (firstCar.GetType().Name == secondCar.GetType().Name) Console.WriteLine("We are both the same type!"); else Console.WriteLine("We are different types!"); // Show all the details. Console.WriteLine(); ReflectOverAnonymousType(firstCar); ReflectOverAnonymousType(secondCar); }

When run code:


3.1Is the first conditional test?

3.2 Is the second conditional test?

3.3 Are

firstCar and secondCar same properties?

3.4 Which is properties of them?(

firstCar and secondCar).

13/13

Vous aimerez peut-être aussi