Sunday, February 28, 2010

Var data type and C# typing

Var data type and C# typing

Release of C# 3.0 was blessed with the new keyword ‘Var’. Var allows you to declare a new variable, whose type is implicitly inferred from the expression used to initialize the variable.

Question is: Does Var affect the typing of the languages? Does C# version 3.0 is less statically typed than its previous versions?

Answer is No. Var does not affect the typing status of the language. C# still remains a statically typed language.

Let’s consider the below statement:

var x = "Sweet Var";

No errors are present in this statement.

Now, if we look at the definition of the dynamic type, it claims that In Dynamic Type, Values have type but Variables do not’.

So, don’t you think above statement, makes the Var declaration a good candidate for dynamic typing?

Well, the answer is No. Look at the below statement:

var x = "Sweet Var";

x = 1;

Error: Cannot implicitly convert type 'int' to 'string'

It means, compiler has the complete knowledge of the data type of the variable X (inferred from the type of value it has). So, above statement is nothing but a wrapper provided to a lazy developer (Not always. It has good usage for Anonymous types and many more), somewhat similar to the Extension Methods (a good candidate for my next blog J). So, I can assume how compiler will process the Var statement:

COMPILE: var x = "Sweet Var";

RAISE: GotALazyDeveloper(x, string);

REPLACE: (var x, String x)

COMPILE: Sting x = "Sweet Var";

Tuesday, February 23, 2010

Updating Controls Data in Multithreaded Environment

If you are developing a multithreaded Windows application, there are high chances that data for a single control is being generated by many threads. In other words, any thread can raise a request to update the control which is owned by some other thread. If you are a .Net developer using .Net versions 2.0 onwards, accomplishing the request is not straight forward case. .Net 2.0 onwards, cross thread operations are not permitted (correct word - ‘advised’).

There are several ways in which you can accomplish this:

· This exception is raised by Visual Studio only. If you will run the application out of Visual Studio, CLR will never complain about the cross thread operation.

Therefore, you can use this simple (Bad though) syntax

Control.Data = data;

· If you are really worried about the testing team ( And not about the application ) that any tester might complain this error while testing the code through Visual Studio, then you can suppress this exception also. You need to instruct Visual Studio to shut up on any cross thread operation:

CheckForIllegalCrossThreadCalls = false;

· If you are concerned about the application and have sense of good programming, then I don’t think above two Options are good for you. One way is to use the invoke method on the control. Each control has a property [Control.InvokeRequired] which can tell you whether control has been created by the current thread or any other thread.

You can use Invoke method to update the control’s state.

** UpdateUIDel -> Delegate

** UpdateUI ->Method to update the controls’ state (i.e. text in a textbox).

delegate void UpdteUIDel(int a);

private void UpdateUI(Object a)

{

textBox1.Text = a.ToString();

}

// Call Invoke on Form itself

this.Invoke(new UpdteUIDel(UpdateUI), val);

· Here is the last method which I think is the best way to solve the problem. .Net does provide SynchronizatinContext class for propagating a synchronization context in various synchronization models. For Windows forms, corresponding context class is the WindowsFormsSynchronizationContext which provides a synchronization context for the Windows Forms application model and is the child class of the SynchronizatinContext.

This class takes the responsibility to identify the control’s owner and updates the control via the same owner.

WindowsFormsSynchronizationContext context = new

WindowsFormsSynchronizationContext();

SendOrPostCallback updateDel = new SendOrPostCallback(UpdateUI);

// Syncronous Method

context.Send(updateDel, val);

// Asynchronous Methods

// context.Post(updateDel, val);

Send is synchronous call (similar to Invoke )

Post is asynchronous call (similar to BeginInvoke)

Sunday, February 7, 2010

Interesting Question...

Question was: Guys tell me how to print both 'if' and 'else' block in a program..

I gave following solution (But still wondering about the requirement?)


int main(void)
{
int a=2;
A:
a--;
if(a>0)
{
/* write ur code */

goto A;
}
else
{
/* write ur code */
}

return 0;
}


Design Problem - Share the Common Instance of Base Class



Here is the problem statement (might sound weird):

I one of my previous project, one guy asked me the solution of a problem. And the problem was:

“Class A and B are child class of Base i.e. ‘A’ and ‘B’ are derived from ‘Base’ Class. Now Base class containing some reference of the other utility classes which are supposed to be common across A and B. So, I want to use the single instance of class Base class. When I am creating instance of any child class (say A), it’s instantiating Base class and its utility objects. After this, when I am creating the instance of class B, again it’s instantiating class B and its utility objects which I WANT TO STOP.[see image BaseClassStructure.jpg]

There was no definite sequence of initialization of child classes.

When I looked @ the base class, I was surprised by the design of the classe. Only correct thing was the name of the Base class J (it was serving its purpose). Base class was not serving any purpose as a parent class. I recommended to change the design. Instead of inheritance, I recommended association of Base class with A and B. [see image IndependentClassStructure.jpg]

Few points about the problem:

· Initially that guy was not agree to change the design. So, he asked me to tell me a way to implement this.

I tried for sometime, but I could not stop the initialization of base class on child class instantiation. I was really wondering if there is any way to do this. I was failed to provide the code to support the design
(though bad)

· Today I was going through singleton implementation and suddenly I got one idea to implement the above discussed design.

Check Program.cs. [Here, Utility is class ‘Use’]

Still I am not sure when any one will go for such design.

Any idea when such type of design/ implementation will be useful?

Here is the implementation:

public class Program

{

public static void Main()

{

ChildSengleton obj1 = new ChildSengleton();


Child2Sengleton obj2 = new Child2Sengleton();


obj1.PrintCount();

obj2.PrintCount();

}


}


class Use

{

public static int count = 1;


public Use()

{

count++;

}


public int Count

{

get { return count; }

}

}


public class Singleton

{

private static Singleton instance = new Singleton(1);

private Use useobj;


protected Singleton()

{

}


private Singleton(int count)

{

useobj = new Use();

}


public static Singleton BaseRef

{

get

{

return instance;

}

}


public int Count

{

get

{

return instance.useobj.Count;

}

}


}


public class ChildSengleton : Singleton

{


public void PrintCount()

{

Console.WriteLine(this.Count);

}

}


public class Child2Sengleton : Singleton

{

public void PrintCount()

{

Console.WriteLine(this.Count);

}

}