Wednesday, February 17, 2010

.Net Framework Application Development Foundation(2)

Code Explanation of C# Languege:

1. object (base method )
class Program
{
static void Main(string[] args)
{
// any object class includes 4 methods : Equals() ,ToString() ,GetType() , GetHashCode() ;
Student aStud = new Student(){ Age = 20, Name = "Jim Parson",Subject = "History"};
Student bStud = new Student() { Age = 20, Name = "Jim Parson", Subject = "History" };

Console.WriteLine(aStud.GetType());// reflection base method
Console.WriteLine(aStud.Equals(bStud));
Console.WriteLine(aStud == bStud);
Console.WriteLine( aStud.GetHashCode());
aStud.Age = 25;
aStud.Name = "tom";
aStud.Subject = "English";
Console.WriteLine(aStud.GetHashCode());
Console.WriteLine(bStud.GetHashCode());
Console.WriteLine(aStud.ToString());
return;
}

class Student
{
// automatical property
public string Name { set; get; }
public int Age { set; get; }
public string Subject { set; get; }

public override bool Equals(object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");

var other = obj as Student;// obj should be Student class object
return (other != null && other.Age == Age && other.Name == Name && other.Subject == Subject);
}

public override int GetHashCode()
{
return (Name +":" + Age +":"+ Subject).GetHashCode();
}

public static bool operator ==( Student a , Student b)
{
if( ReferenceEquals(a,b))// Object.ReferenceEquals( a , b)
return true;

if ((object)a == null || (object)b == null)
return false;

return a.Equals((b));

}

public static bool operator !=(Student a, Student b)
{
return !(a == b);
}

public override string ToString()
{
return Name + " : " + Age + " : " + Subject;
}
}

2. var keyword ( I love using it)
//*** C# support double type number reminder ***
//Console.WriteLine(7.2%2.4);
//return;

//*** C# Definite Assignement Rule ***
// int aNum;
//Console.WriteLine(aNum);
// or using out keyword
//var afloat = 12f;
//var adouble = 24.5;
//var money = 21.35m;
//Console.WriteLine("{0} {1} {2} {3} {4}" , num , str, afloat,adouble,money);

//Console.WriteLine( "this is a nice day." + "that is right.");
//string input = Console.ReadLine();
//int another;
//if( int.TryParse( input, out another ))
// Console.WriteLine(another);
// int aNum = int.Parse(input);

//*** C# is case-sensitive language ***
//int integer = 100, integEr = 200;
//Console.WriteLine( "{0} -- {1}" , integer , integEr)

3. List , Array , Lambda ,ForEach()
// list has ForEach() , linq to object always uses list
int[] arr = {10, 40, 43, 55, 67, 35, 6, 78, 9};
var alist = arr.ToList();
alist.ForEach(Console.WriteLine);// == alist.ForEach( item=>Console.WriteLine(item));

4.Switch Statement

string input = Console.ReadLine();
switch (input) // input could int type , char or string , no float , double
{
case "1" :
Console.WriteLine("input is 1");
break;
case "2": // can fall-through
case "3":
Console.WriteLine("input is 2 or 3");
break;
case "4":
Console.WriteLine("input is 4");
break;
default :
Console.WriteLine("default input");
break;
}
4. Overflow Exception : checked and unchecked
int n = int.MaxValue;
try
{
checked // or unchecked
{
n += 1;
Console.WriteLine("overflow?");

}
}
catch (OverflowException e)
{
Console.WriteLine("overflow found");
}

byte test = 240;
byte another = 120;
test = unchecked((byte)(test + another));
Console.WriteLine(test);
test = 240;
test = checked((byte)(test+ another) );

5. Class Student -- Constructors
///
/// all kinds of constuctors
///

///
///
///
public Student( string _name , int _age , string _sub)
{
Name = _name;
Age = _age;
Subject = _sub;
}
public Student( string _name , int _age):this(_name ,_age , "N/A")
{

}

public Student( string _name):this(_name , 18)
{
}

public Student( int age):this("noName" , age )
{
}
public Student():this("unknown")
{
}

6. Const and Readonly (the same use but readonly type can be used in run time
class Media
{
public const int Month = 12;
// error => public const DateTime Current = DateTime.Now.Year;
public readonly DateTime Current = DateTime.Now;
}

7. Static Class in C#
public static class Shape
{
public static int Area { set; get; } //property

private static int _field; // field

public static void Show()
{
throw new NotImplementedException();
}
}

8.Anonymous Class
var anonymousClass = new {Name = "Tom", Age = 20};
Console.WriteLine(anonymousClass);
or
string atr = "this is a good movie." ;
var other = atr.split( new [] { " "}) ;
or In Linq Application

9. Nullable and Nullable<T>  --we always use generics one
Nullable<int> num = null; // or int? num = null or Enumeration Type
num = 100;
if(num.HasValue)
Console.WriteLine(num);
Console.WriteLine(num.GetType());

10. Boxing and unboxing
int one = 100;
object other = one; // boxing
one = (int) other; // unboxing
Console.WriteLine(one);

11. Is and As Operator ( in Type Cast )
Student aStud = new Student(){ Age = 20, Name = "Jim Parson",Subject = "History"};
object obj2 = aStud; //
var other2 = obj2 as Student;//
if( other2 != null )//
Console.WriteLine("it is Student Type");//
return;
or
Student aStud = new Student(){ Age = 20, Name = "Jim Parson",Subject = "History"};
object obj = aStud;
var other = obj;
if( other is Student)
Console.WriteLine("yes");

12.Enumeration
enum Days :byte { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri }; // not be defined in a method

13. Array copy
int[] arr = {5, 9, 2, 4, 8};
var another = (int[]) arr.Clone();
//var another = new int[arr.Length];
//Array.Copy(arr, another, arr.Length);
//arr.CopyTo(another , 0);
another.ToList().ForEach(Console.WriteLine);

14. extension method
static class MyClass
{
public static int IntegerPart( this double a)
{
return Convert.ToInt32(a);
}
}
class Program
{  
  static void Main(string[] args)
{
double num = 6.5;
Console.WriteLine(num.IntegerPart());
   return ;
}
}

15. Interface ( explicitly and implicitly)
internal interface ITalk
{
void Talk();
bool WantToTalk();
}

internal interface ISpeak
{
void Speak();
bool WantToTalk();
}

internal class AClass : ITalk , ISpeak
{
public void Talk()
{
Console.WriteLine("method Talk called");
}
bool ITalk.WantToTalk()
{
Console.WriteLine("method ITalk.WantToTalk called");
return true;
}
bool ISpeak.WantToTalk()
{
Console.WriteLine("method ISpeak.WantToTalk called");
return false;
}
public virtual void Speak()
{
Console.WriteLine("method speak called");
}

public void PrintAll()
{
Console.WriteLine("All Information.");
}
}

class Program
{
static void Main(string[] args)
{
AClass anotherOne = new AClass();

anotherOne.Speak();// object cannot call explicitly interface methods
anotherOne.Talk();

ITalk anInter = anotherOne; // the interface variable can only call its own methods
anInter.Talk();
anInter.WantToTalk();

ISpeak anInter2 = anotherOne;
anInter2.Speak();
anInter2.WantToTalk();
}}

16. Abstract Class
class Library where T : Media
{
public List Items { get; set; }
}

abstract class Media
{
public string ISBN { get; set; }
}

class Book : Media
{
}

class Dvd : Media
{
}

17. Property
public class InterClass
{
public string Name { set; get; }
public int ID { get; private set; } //read only property
public string Score { set; private get; } // write only
}
static void Main(string[] args)
{
InterClass anotherOne = new InterClass() { Name = "Tom", Score = "30"};
}

18.Generic Class
class Media
{
public string ISDN { set; get; }
}
class Book:Media{}
class DVD : Media{}
class Library<T> where T:Media
{
public List
<T> Item { get; set; }
}

19. LINQ to Objects
var addresses = new[]
{
new {CompanyName = "ASK", City = "Tokyo", Country = "Japan"},
new {CompanyName = "TPG", City = "Sydney", Country = "Australia"},
new {CompanyName = "Nissan", City = "Osaka", Country = "Japan"},
new {CompanyName = "Toshiba", City = "Tokyo", Country = "Japan"},
new {CompanyName = "ALG", City = "New York", Country = "USA"}
};

var customers = new [] // anonymous array
{
new { CID = 1,FName = "Tim", SName = "Anderson", Age = 23 , CompanyName="ASK"},
new { CID =2,FName = "Loly", SName = "Green", Age = 22,CompanyName="TPG"},
new{ CID =3,FName = "Tom" ,SName="Lee" , Age=21 ,CompanyName="ALG"} ,
new{ CID =4,FName = "Bob" ,SName="Camp" , Age=23,CompanyName="Toshiba"} ,
new{ CID =5 ,FName = "Jason" ,SName="Troops" , Age=24,CompanyName="ALG"} ,
};// like a table

//var firstnames = customers.Select(name => name.FName + " " + name.SName +"--"+ name.Age);//Select statement
var firstnames = from name in customers select new {name.FName, name.SName, name.Age};
//var fullItems = customers.Select(item => new {FullName = item.FName + " " + item.SName, Age = item.Age});
//var filter = customers.Where(age => int.Equals(age.Age, 23)).Select(aname => aname.FName);//where statement
var filter = from age in customers where int.Equals(age.Age, 23) select age.FName;
//var orderBy = customers.OrderByDescending(order=>order.Age).Select(aname => aname.FName);//order by statement
var orderBy = from order in customers orderby order.Age descending select order.FName;
//var joins = customers.Select(c => new {c.FName, c.SName, c.CompanyName}).Join(addresses,
// cust => cust.CompanyName,
// addr => addr.CompanyName,
// (cust, addr) =>
// new
// {
// cust.FName,
// cust.SName,
// addr.City
// });
var joins = from c in customers
join a in addresses on c.CompanyName equals a.CompanyName
select new {c.FName, c.SName, a.City};
foreach (var item in firstnames)
{
Console.WriteLine(item);
}
Console.WriteLine();
//foreach (var item in fullItems)
//{
// Console.WriteLine(item);
//}
Console.WriteLine();
foreach (var e in filter)
{
Console.WriteLine(e);
}
Console.WriteLine();
foreach (var o in orderBy)
{
Console.WriteLine(o);
}
Console.WriteLine();
Console.WriteLine(customers.Select(cust => cust.Age).Distinct().Count());
foreach (var j in joins)
{
Console.WriteLine(j);
} }

20.IEnumerable , IEnumerator and yield statement
class Program
{
static void Main(string[] args)
{
AClass app = new AClass();

foreach (var @class in app.ShowMe())
{
Console.WriteLine(@class);
}

var iterator = app.GetEnumerator();
while( iterator.MoveNext())
{
Console.WriteLine(iterator.Current);
}
// iterator.Reset();reset method not implemented
return;

}
}

class AClass
{
private int[] arrInt = {1, 2, 3, 4, 5, 6, 7, 8, 9};
public IEnumerator GetEnumerator()
{
foreach (var i in arrInt)
{
if( i == 6)
yield break;

yield return i;
}
}
public IEnumerable ShowMe()
{
foreach (var i in arrInt)
{
yield return i;
}
}
}

21.delegate , Event , covariance and contravariance
class Program
{
public static void Show()
{
Console.WriteLine("show something to me.");
}
public static void Handler( object sender , EventArgs args)// subscriber
{
Console.WriteLine("yes , I subscribed this event.");
}

static void Main(string[] args)
{
BClass another = new BClass() {Name = "James", SCode = 939483};
BClass.AHandler del = another.PrintName;
del += another.PrintSCode;
del += Show;

//del();
del -= another.PrintName;//remove a delegation
del += another.PrintName;//add it again
del.Invoke();

Console.WriteLine( );
foreach (var s in del.GetInvocationList())
{
Console.WriteLine(s.Method.Name);
}
del = null;

another.MyEvent += Handler;
another.AMethod();//invoke event

}
}

class BClass
{
public delegate void AHandler();
// define an event
public event EventHandler MyEvent;

public string Name { set; get; }
public int SCode { set; get; }

public void PrintName()
{
Console.WriteLine(this.Name);
}
public void PrintSCode()
{
Console.WriteLine(this.SCode);
}
// invoke an event
public void AMethod()
{
if (this.MyEvent != null)
MyEvent(null, null);
}
}

No comments:

Post a Comment