Thursday 12 February 2009

c# 3.0 - Session 2 (Implicitly typed varibles)

Session Overview 2 (Implicitly typed variables)

Local Type Inference (aka Implicitly Typed Local variables)
var keyword
Emphasis on local, as in local scope.


NOTE: var cannot be used in the following cases

As a return value from function
Uninitialized variables
Null assignment


using System;
using System.Collections.Generic;
using System.Linq;

public class csharp3_2
{
public static void RunSnippet()
{
var num = 1;
Console.WriteLine("Typeof num is {0}", num.GetType());
var name = "rajesh";
Console.WriteLine("Typeof name is {0}", num.GetType());
string[] countries = new string[] { "India", "US", "Israel", "China"};
var iCountries = from c in countries
where c.StartsWith("I")
select c;
foreach(var c in iCountries)
Console.WriteLine(" Country starting with I {0}", c);
}


#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format
("---\nThe following error occurred while executing

the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}

private static void Break()
{
System.Diagnostics.Debugger.Break();
}

#endregion
}

Session Oveview 2 (Local Type Inference)

Session Oveview 2 (Local Type Inference)

 Local Type Inference (aka Implicitly Typed Local Variable)
 Var keyword (make development easier)
 Emphasis on local, as in local scope.

NOTE: Var keyword works only with local scope.

e.g.
var first = 1; // first will be of type System.Int32
Console.WriteLine (“Type of first {0}”, first.GetType()):
var name = “rajesh”; // name will be of type System.String
Console.WriteLine (“Type of name {0}”, first.GetType()):

Points to note:
1. var canno be part of a return value of a function.
2. var order; This is invalid as this has to be initialized.
3. var forth = null; This is invalid as null is basically unknown.
Some examples:
String[] countries = new string[]
{“India”, “China”, “Israel”, “Russia”};
// get all countries which starts with “I”
var iCountry = from c in countries
where c.StartsWith(“I”)
select s;
foreach(var country in iCountry)
Console.WriteLine(country);

The output of the above snippet will be
India
Israel

c# 3.0 - Session 1

Session Overview 1 (Auto Implemented Properties)

  • Auto Implemented Properties
  • Prop and propg
Auto Implemented Properties allows you to implement public accessors for your classes private field quickly.

Following is the syntax to declare public accessor for the private field

For shortcut type “prop” and press tab twice.

For e.g. to declare employeeName field use the following shortcut.
public string EmployeeName { get; set; }


For readonly property type “propg” and hit tab twice.
public DateTime OrderDate { get; private set;}