Wednesday, December 16, 2009

synchronize method in dotNet c# - Method Synchronization

Synchronized methods give us an ability to execute only one thread at a time. This is useful if our method modifies global variable.

using System.Runtime.CompilerServices;

[MethodImpl(MethodImplOptions.Synchronized)]
public Boolean Check()
{
if(quantity>buyQuantity)
{
decreaseQuantity(buyQuantity);
}
}

Its similar to java like... for Java it will be...

public class SynchronizedCounter {
private int c = 0;

public synchronized void increment() {
c++;
}
}

Simply........

Specifies that the method can be executed by only one thread at a time. Static methods lock on the type, while instance methods lock on the instance. Onlyone thread can execute in any of the instance functions and only one thread can execute in any of a class's static functions.

Saturday, December 12, 2009

Tuesday, December 8, 2009

Operator Overloading, Method Overriding Exampl


void Main()
{
 S1 s1 = new S1("hello");
 S1 s2 = new S1("hello");
 
 (s1 == s2).Dump();
 (s1.Equals(s2)).Dump();
 
 (s1.GetHashCode() == s2.GetHashCode()).Dump();
 
}

class S1
{
 string _name;
 public S1(string name)
 {
  _name = name;
 }
 
 public override string ToString()
 {
  return _name??"";
 } 
 
 public override bool Equals(object x)
 {
  "Equals Called".Dump();
  return _name.Equals(x.ToString());
 }
 public static bool operator ==(S1 s1,S1 s2)
 {
  if (s1._name == s2._name)
   return true;
  else
   return false;
 }
 public static bool operator !=(S1 s1, S1 s2)
 {
  if (s1._name != s2._name)
   return false;
  else 
   return true;
 }
}
// Define other methods and classes here

Learn as you go - C# developer

Tired from creating projects for testing and learning C#, Try brand new Linq Pad for your C# learning Practice.
Download From: http://www.linqpad.net/