Now developer can view the source code of .NET Framework. So we can know what is really going on inside .NET. Pair with Visual Studio, we can also debug the code.
http://weblogs.asp.net/scottgu/archive/2008/01/16/net-framework-library-source-code-now-available.aspx
Search This Blog
Showing posts with label C# Djvu. Show all posts
Showing posts with label C# Djvu. Show all posts
Thursday, September 10, 2009
Wednesday, July 1, 2009
C# Collections
using System;
using System.Collections.Generic;
using System.Text;
namespace chap5_collections
{
public class Class1
{
static void Main()
{
//5.2 reversing an array average time, N/2
int[] someArray = new int[] { 1, 2, 3, 4, 5 };
//or int[] someArray = new int[5] { 1, 2, 3, 4, 5 };
ReverseHelper reverseHelper = new ReverseHelper();
reverseHelper.reverse(someArray);
foreach (int i in someArray) Console.WriteLine(i);
//or we can just use .Net
Array.Reverse(someArray);
foreach (int i in someArray) Console.WriteLine(i);
//5.2.1 reverse a stirng
string tryReverseString = "ABCDEFGHI";
string reverseTryReverseString = new String(tryReverseString.ToCharArray().Reverse().ToArray());
//5.2.1 use customize helper to reverse a string
StringBuilder reverseStringBuilder = new StringBuilder(tryReverseString);
reverseHelper.reverseString(reverseStringBuilder);
for (int i = 0; i <> myDataList = new List();
myDataList.Add(new Data(5));
myDataList.Add(new Data(2));
myDataList.Add(new Data(3));
int total = 0;
myDataList.ForEach(delegate(Data obj)
{
total += obj.Value;
});
Console.WriteLine("total is:{0}", total);
}
}
public class Data
{
//remember to declare constructor public
public Data(int value)
{
Value = value;
}
public int Value { get; set; }
}
public class ReverseHelper
{
public void reverse(T[] theArray)
{
T tempArray = default(T);
for (int i = 0; i < theArray.Length / 2; ++i)
{
tempArray = theArray[theArray.Length - 1 - i]; //store the back (among second half)
theArray[theArray.Length - 1 - i] = theArray[i]; //set back = front, back is lost
theArray[i] = tempArray; // restore front with the old back
}
}
public void reverseString(StringBuilder s)
{
//tringBuilder temp = new StringBuilder(1);
char temp = new char();
for (int count = 0; count < s.Length/2; ++count)
{
temp = s[s.Length - 1 - count];
s[s.Length - 1 - count] = s[count];
s[count] = temp;
}
}
}
}
source code: http://code.google.com/p/mixtools/source/browse/#svn/trunk/c#/cookbook/chap5_collections/chap5_collections
using System.Collections.Generic;
using System.Text;
namespace chap5_collections
{
public class Class1
{
static void Main()
{
//5.2 reversing an array average time, N/2
int[] someArray = new int[] { 1, 2, 3, 4, 5 };
//or int[] someArray = new int[5] { 1, 2, 3, 4, 5 };
ReverseHelper reverseHelper = new ReverseHelper();
reverseHelper.reverse
foreach (int i in someArray) Console.WriteLine(i);
//or we can just use .Net
Array.Reverse(someArray);
foreach (int i in someArray) Console.WriteLine(i);
//5.2.1 reverse a stirng
string tryReverseString = "ABCDEFGHI";
string reverseTryReverseString = new String(tryReverseString.ToCharArray().Reverse().ToArray());
//5.2.1 use customize helper to reverse a string
StringBuilder reverseStringBuilder = new StringBuilder(tryReverseString);
reverseHelper.reverseString(reverseStringBuilder);
for (int i = 0; i <> myDataList = new List();
myDataList.Add(new Data(5));
myDataList.Add(new Data(2));
myDataList.Add(new Data(3));
int total = 0;
myDataList.ForEach(delegate(Data obj)
{
total += obj.Value;
});
Console.WriteLine("total is:{0}", total);
}
}
public class Data
{
//remember to declare constructor public
public Data(int value)
{
Value = value;
}
public int Value { get; set; }
}
public class ReverseHelper
{
public void reverse
{
T tempArray = default(T);
for (int i = 0; i < theArray.Length / 2; ++i)
{
tempArray = theArray[theArray.Length - 1 - i]; //store the back (among second half)
theArray[theArray.Length - 1 - i] = theArray[i]; //set back = front, back is lost
theArray[i] = tempArray; // restore front with the old back
}
}
public void reverseString(StringBuilder s)
{
//tringBuilder temp = new StringBuilder(1);
char temp = new char();
for (int count = 0; count < s.Length/2; ++count)
{
temp = s[s.Length - 1 - count];
s[s.Length - 1 - count] = s[count];
s[count] = temp;
}
}
}
}
source code: http://code.google.com/p/mixtools/source/browse/#svn/trunk/c#/cookbook/chap5_collections/chap5_collections
C# Delegate, Events, and Anonymous Methods
- Why use event?
- Why use generic delegate?
- How to use asynchronous delegate? (BeginInvoke)
- Why use generic EventHandler
delegate? - Anonymous method with delegate
*event in c# is delegate, usually named "eventHandler" and takes some arguments
*by convention, c# use OnEvent() as a wrapper to call and pass arguments.
which then invoke the event (calling the delegate; invoke the callback that event handler has registered with. it is also why we usually check if the event is null (no callback yet, don't call it)
*More concepts: event is just a callback. in c# event can registered multiple methods. fire the event will call all the registered methods. also, signal is a callback with multiple target (think of an Qt signal connects to many slots). signal is also called event or publisher. for slot, it is also called event target, subscriber, or callback receiver)
Remember this form to declaring the event
//p349, p364, Pro C#2008 a. declare delegate type, b. define member variable
public delegate void CardHandler(string s);
public event CardHandler accelerate;
| using System; |
| using System.Runtime.Remoting.Messaging; |
| namespace chap9_delegate |
| { |
| public class Class1 |
| { |
| static void Main() |
| { |
| //9.1 GetInvocationList to obtain an array of Delegate objects |
| Multicast multicast = new Multicast(); |
| multicast.useMulticastDelegate(); |
| //9.2 You can get the return value of multicast delegate |
| //9.3 Catch individual exception in a multicast delegate |
| //9.4 asynchronous delegate |
| //9.5 wrap in sealed class, FileSystemWatcher 12.23 |
| //9.12 anonymous methods, 3 ways to do it |
| Class2 class2 = new Class2(); |
| class2.WorkItOut(); |
| class2.WorkItOutAnonymous(); |
| //9.13 Generic Event Handler //p369, Pro c#2008, |
| //The advantage of using EventHandler<(Of <(TEventArgs>)>) |
| //is that you "do not need to code your own custom delegate" if your event generates event data. |
| //chap 11, pro c#2008, andrew troelsen |
| UnderstandEvent understandEvent = new UnderstandEvent(); |
| //you can register event handler to the accelerate event at the client side, in this case, speedup. |
| //you can directly assign the method name to the event, the IL will write "new" for you |
| understandEvent.accelerate += understandEvent.speedup; |
| //or you can register this way, no syntatic sugar but still work |
| understandEvent.accelerate += new UnderstandEvent.CardHandler(understandEvent.speedup); |
| understandEvent.onAccelerate(); // call speedup twice |
| //p.363,WHY USE EVENT? |
| // the following line will not compile, the "accelerate" event is private to its class! |
| // , so now you can only REGISTER/DE-REGISTER the event handler on accelerate event, |
| // to call the accelerate event, you need to define a public function inside acclerate's class to call it |
| //understandEvent.accelerate("call speedup through event"); |
| // Generic delegate p.360 |
| //what's the point? we can write our delegate once, since the argument in the handler is generic |
| GenericDelegate genericDelegate = new GenericDelegate(); |
| genericDelegate.typeString = new GenericDelegate.myGenericDelegate<string>(genericDelegate.methodTypeString); |
| genericDelegate.typeInt = new GenericDelegate.myGenericDelegate<int>(genericDelegate.methodTypeInt); |
| genericDelegate.typeString("call string type generic delegate"); |
| genericDelegate.typeInt(10); |
| |
| //p.591 c# pro Asyn Delegate |
| //play with the following for method yourself |
| MyAsyncDelegate myAsyncDelegate = new MyAsyncDelegate(); |
| //myAsyncDelegate.runAddManyNumberDelegate1(); |
| //myAsyncDelegate.runAddManyNumberDelegate2(); |
| //myAsyncDelegate.runAddManyNumberDelegate3(); |
| myAsyncDelegate.runAddManyNumberDelegate4(); |
| |
| } |
| } |
| public class Class2 |
| { |
| delegate int DoWork(string s); |
| public void WorkItOutAnonymous() |
| { |
| DoWork dw = delegate(string s) //do not put "new" here; argument and return type must match too |
| { |
| Console.WriteLine(s); |
| return s.GetHashCode(); |
| }; |
| int result = dw("WorkItOutAnonymous"); |
| } |
| public void WorkItOut() |
| { |
| DoWork dw = new DoWork(DoWorkMethodImpl); |
| //C# Magic, same as the above, C# writes the IL to create the delegate object, |
| //no more "new Delegate()" |
| //DoWork dw = DoWorkMethodImpl; |
| int i = dw("DoWorkMethodImpl1"); |
| } |
| public int DoWorkMethodImpl(string s) |
| { |
| Console.WriteLine(s); |
| return s.GetHashCode(); |
| } |
| } |
| public class Multicast |
| { |
| delegate int myDelegate(string s); |
| public void useMulticastDelegate() |
| { |
| myDelegate m1 = new myDelegate(method1); |
| myDelegate m2 = new myDelegate(method2); |
| myDelegate m3 = new myDelegate(method3); |
| myDelegate myDelegateMulticast = m1 + m2 + m3; |
| //myDelegate[] allMethodInMyDelegate = (myDelegate[])myDelegateMulticast.GetInvocationList(); //does not work |
| Delegate[] allMethodInMyDelegate = myDelegateMulticast.GetInvocationList(); |
| for (int i = 0; i < allMethodInMyDelegate.Length; ++i) |
| { |
| int returnValue; //we can capture each return value from each delegate |
| returnValue = ((myDelegate)allMethodInMyDelegate[i])(string.Format("{0}, this is the argument string", i)); |
| } |
| } |
| public int method1(string s) |
| { |
| Console.WriteLine(s); |
| return 1; |
| } |
| public int method2(string s) |
| { |
| Console.WriteLine(s); |
| return 2; |
| } |
| public int method3(string s) |
| { |
| Console.WriteLine(s); |
| return 3; |
| } |
| } |
| public class UnderstandEvent |
| { |
| //p349, p364, Pro C#2008 a. declare delegate type, b. define member variable |
| public delegate void CardHandler(string s); |
| public event CardHandler accelerate; |
| public void speedup(string s) |
| { |
| Console.WriteLine(s); |
| } |
| public void onAccelerate() |
| { |
| if (accelerate != null) |
| { |
| accelerate("accelerated event is invoked"); |
| } |
| else |
| { |
| Console.WriteLine("you must register (listening the incoming event before calling the event"); |
| } |
| } |
| } |
| public class GenericDelegate |
| { |
| public delegate void myGenericDelegate<T>(T myGenericType); |
| public myGenericDelegate<string> typeString; |
| public myGenericDelegate<int> typeInt; |
| |
| public void methodTypeString(string s) { Console.WriteLine("call method type string"); } |
| public void methodTypeInt(int s) { Console.WriteLine("call method type int"); } |
| } |
| public class MyAsyncDelegate |
| { |
| public delegate int myDelegate(string s); |
| public int addManyNumber(string s) |
| { |
| Random random = new Random(); |
| int ret = 0; |
| for (int i = 0; i < 1000; ++i) |
| ret += random.Next(500); |
| return ret; |
| } |
| public int runAddManyNumberDelegate1() |
| { |
| myDelegate md = new myDelegate(addManyNumber); |
| //or, myDelegate md = addManyNumber; |
| //this will return right away |
| IAsyncResult iftAR = md.BeginInvoke("run beginInvoke", null,null ); |
| //busy loop to appreciate the multithreading feeling |
| while (!iftAR.IsCompleted) |
| { |
| Console.WriteLine("MyAsyncDelegate is not completed"); |
| } |
| Console.WriteLine("\n\nMyAsyncDelegate is now compleged"); |
| //calling thread is now blocked until EndInvoke is completed |
| int answer = md.EndInvoke(iftAR); |
| return answer; |
| } |
| //AsyncCallback |
| public int runAddManyNumberDelegate2() |
| { |
| myDelegate md = addManyNumber; |
| IAsyncResult itfAT = md.BeginInvoke("run beginInvoke", messageCallback1, null); |
| int answer = 0; |
| return answer; |
| } |
| //the callback for BeginInvoke, the sygnature must be the following pattern |
| //Note the IAsyncResult argument |
| public void messageCallback1(IAsyncResult itfAR) |
| { |
| Console.WriteLine("beginInvoke compleged, callback call!"); |
| } |
| public int runAddManyNumberDelegate3() |
| { |
| myDelegate md = addManyNumber; |
| md.BeginInvoke("dummy arg", messageCallback2, null); |
| int answer = 0; |
| return answer; |
| } |
| // so you can get the reference of the orignal delegate from the callback |
| // and you can call EndInvoke to get the return value from the orignal delegate |
| public void messageCallback2(IAsyncResult iftAR) |
| { |
| Console.WriteLine("messageCallback2 call, beginInvoke completed"); |
| AsyncResult ar = (AsyncResult)iftAR; |
| myDelegate md = (myDelegate)ar.AsyncDelegate; |
| //calling thread is no blocked until EndInvoke is compleged |
| int returnValueFromDelegate = md.EndInvoke(iftAR); |
| Console.WriteLine("return value from messageCallback2 is {0}:", returnValueFromDelegate); |
| } |
| //use the last argument in BeginInvoke |
| public int runAddManyNumberDelegate4() |
| { |
| myDelegate md = addManyNumber; |
| md.BeginInvoke("dummy arg", messageCallback3, "Stuff in the last argument in BeginInvoke"); |
| int answer = 0; |
| return answer; |
| } |
| //use AsyncState |
| public void messageCallback3(IAsyncResult iftAR) |
| { |
| Console.WriteLine("messageCallback3 call, beginInvoke completed"); |
| string arg = (string)iftAR.AsyncState; |
| Console.WriteLine(arg); |
| } |
| } |
| } |
Sunday, June 28, 2009
C# String and StringBuilder
Which to choose?
Use string to represent basic data, such as header or title, string is excellent. For characters used in text processing, use StringBuilder.
C# string is immutable, so
string s = "my string";
s = "new string";
"my string" will be garbage collected.
--------------------------------------
If this happens frequently, such as string concatenation s3 = s1+s2 in a loop, use StringBuilder. It pre-allocated enough space at first.
StringBuilder s = new StringBuilder("more string here", 256);
s.Append("more here..");
s.AppendLine("more more...");
Use string to represent basic data, such as header or title, string is excellent. For characters used in text processing, use StringBuilder.
C# string is immutable, so
string s = "my string";
s = "new string";
"my string" will be garbage collected.
--------------------------------------
If this happens frequently, such as string concatenation s3 = s1+s2 in a loop, use StringBuilder. It pre-allocated enough space at first.
StringBuilder s = new StringBuilder("more string here", 256);
s.Append("more here..");
s.AppendLine("more more...");
Tuesday, June 23, 2009
C# Strings and Characters
C# Cookbook Chapter 2
using System.Text;
namespace chapter2_string
{
public class Class1
{
static void Main()
{
Console.WriteLine(Char.IsLetter('a')); //true
Console.WriteLine(Char.IsNumber("123412",2)); //treu
Console.WriteLine('a'.Equals('b')); //false
Console.WriteLine('a' > 'b'); //false
string splitTestString = "today is, a good= day. yes";
string[] splitTestResult = splitTestString.Split(new char[4] { ' ', ',', '=', '.' });
foreach (string tok in splitTestResult) Console.WriteLine(tok);
Console.WriteLine("str".EndsWith("r")); //true
StringBuilder sourceString = new StringBuilder("this is a string");
sourceString.Insert(1, "\"INSERTED STRING HERE\"");
Console.WriteLine(sourceString);
StringBuilder stringBuilderRemoveStr = new StringBuilder("1234abc5678", 12); //capacity
stringBuilderRemoveStr.Remove(4, 3);
Console.WriteLine(stringBuilderRemoveStr);
StringBuilder stringBuilderReplace = new StringBuilder("123==");
stringBuilderReplace.Replace('=', '!');
Console.WriteLine(stringBuilderReplace);
string intString = "123";
int theInt = Int32.Parse(intString);
string DoubleString = "-234.234";
double theDouble = Double.Parse(DoubleString);
string boolString = "true";
bool theBoolean = Boolean.Parse(boolString);
string testFormat = string.Format("abcdefg{0}ijklmn{1}", 'h', "o");
Console.WriteLine(testFormat);
string[] testJoin = new string[5] { "a", "b", "c", "d","f"};
string joinResult = string.Join(":", testJoin);
Console.WriteLine(joinResult);
string iterateString = "abc";
foreach (char s in iterateString) Console.WriteLine(s);
//or
for (int i = 0; i < iterateString.Length; ++i) Console.WriteLine(iterateString[i]);
string trimTest = "--TEST// ";
Console.WriteLine(trimTest.Trim(new char[3] { '-', ' ', '/' })); //Print TEST
StringBuilder appendLineTest = new StringBuilder("single line");
appendLineTest.AppendLine(); //platform-indepedent new line added.
Console.WriteLine(appendLineTest);
- Encoding 2.11, 2.12, 2.13, 2.26
- Performance: 2.21 intern pool, 2.22 set capacity on a StringBuilder
using System.Text;
namespace chapter2_string
{
public class Class1
{
static void Main()
{
Console.WriteLine(Char.IsLetter('a')); //true
Console.WriteLine(Char.IsNumber("123412",2)); //treu
Console.WriteLine('a'.Equals('b')); //false
Console.WriteLine('a' > 'b'); //false
string splitTestString = "today is, a good= day. yes";
string[] splitTestResult = splitTestString.Split(new char[4] { ' ', ',', '=', '.' });
foreach (string tok in splitTestResult) Console.WriteLine(tok);
Console.WriteLine("str".EndsWith("r")); //true
StringBuilder sourceString = new StringBuilder("this is a string");
sourceString.Insert(1, "\"INSERTED STRING HERE\"");
Console.WriteLine(sourceString);
StringBuilder stringBuilderRemoveStr = new StringBuilder("1234abc5678", 12); //capacity
stringBuilderRemoveStr.Remove(4, 3);
Console.WriteLine(stringBuilderRemoveStr);
StringBuilder stringBuilderReplace = new StringBuilder("123==");
stringBuilderReplace.Replace('=', '!');
Console.WriteLine(stringBuilderReplace);
string intString = "123";
int theInt = Int32.Parse(intString);
string DoubleString = "-234.234";
double theDouble = Double.Parse(DoubleString);
string boolString = "true";
bool theBoolean = Boolean.Parse(boolString);
string testFormat = string.Format("abcdefg{0}ijklmn{1}", 'h', "o");
Console.WriteLine(testFormat);
string[] testJoin = new string[5] { "a", "b", "c", "d","f"};
string joinResult = string.Join(":", testJoin);
Console.WriteLine(joinResult);
string iterateString = "abc";
foreach (char s in iterateString) Console.WriteLine(s);
//or
for (int i = 0; i < iterateString.Length; ++i) Console.WriteLine(iterateString[i]);
string trimTest = "--TEST// ";
Console.WriteLine(trimTest.Trim(new char[3] { '-', ' ', '/' })); //Print TEST
StringBuilder appendLineTest = new StringBuilder("single line");
appendLineTest.AppendLine(); //platform-indepedent new line added.
Console.WriteLine(appendLineTest);
Subscribe to:
Posts (Atom)