Showing posts with label Keyword. Show all posts
Showing posts with label Keyword. Show all posts

Sunday, March 3, 2013

C# V/S VB.Net variable scope in using block

Recently there was a scenario faced by one of our colleague which brought one more difference between C# and VB.Net. Now it is related to the 'using' block.The difference can be summarized as

"In C# if we reinitialize a variable in the header of using block which is declared already in the higher scope,it overwrite the already declared variable.But in VB.Net if we try reinitialize already declared variable it will create a new variable only for the 'using' block.

This is little difficult to understand. Lets see in code.

Code Output
class Disposable : IDisposable
{
    string input;
    public Disposable(string arg)
    {
        input = arg;
    }
    public void Display()
    {
        Console.WriteLine(input);
    }
    public void Dispose(){}
}
public class Program
{
    static Disposable dispo = new Disposable("higher level");
    static void Main(string[] args)
    {
        using (dispo = new Disposable("using block level"))
        {
            dispo.Display();
        }
        dispo.Display();
    }
}


using block level

using block level


Public Class Disposable
    Implements IDisposable
    Dim input As String
    Public Sub New(arg As String)
        input = arg
    End Sub
    Public Sub disp()
        Console.WriteLine(input)
    End Sub
    Public Sub Dispose() Implements IDisposable.Dispose 'Implement later
    End Sub
End Class

Module Module1
    Dim dispo As New Disposable("higher level")
    Sub Main()

        Using dispo = New Disposable("using block level")
            dispo.disp()
        End Using
        dispo.disp()
    End Sub
End Module


using block level

higher level

It is clear that at the first look the code looks same. This type of scenarios may come when we do a C# to VB.Net conversion or vice versa.
If you want to get the C# behavior in VB.Net you need to move the initialization part out of using block header.Code below

dispo = New Disposable("using block level")
Using dispo
    dispo.disp()
End Using
dispo.disp()

Tuesday, November 27, 2012

Difference between IIF and If in VB.Net

In C# the conditional operator ‘?:’ works in a simple fashion and there is only one ternary operator. Early days of  VB.Net was too similar to C# as we had IIF function to achieve the same. But later they added a additional features to if keyword to behave like ternary conditional operator. That change mainly introduced an question into VB.Net interviews. What is the difference between IIF and if keyword.

‘IIF’ is a function which is available in Microsoft.VisualBasic.dll where the ‘if’ is a keyword which is part of the language. Simply speaking you can right click on the IIF and select “Go To Definition”.

IIF always accept 3 parameter. But if can accept 2 parameter. In that case the behavior will be changed in such a way that it returns second param if the first is null.Else the first parameter.

IIF evaluates all three parameter expressions (truepart and false part) regardless the value of first expression. But ‘if’ evaluates either second or third expression based on the value of the first expression.

Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim result As Boolean = IIf(True, TruePart(), FalsePart())
MessageBox.Show("Result :" & result)
End Sub
Public Function TruePart() As Boolean
Console.WriteLine("TruePart!")
Return True
End Function
Public Function FalsePart() As Boolean
Console.WriteLine("FalsePart!")
Return False
End Function

The out put of the above code shows as follows .
Messagebox shows ‘Result :True’ and the output window
TruePart!
FalsePart!


Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim result As Boolean = If(True, TruePart(), FalsePart())
MessageBox.Show("Result :" & result)
End Sub


The out put of the above code shows as follows .
Messagebox shows ‘Result :True’ and the output window shows only
TruePart!

Want to learn more about other features of if keyword such as null alternate please visit the msdn link

Monday, July 16, 2012

Facts about yield keyword.

When I take interview for SE(Software Engg) or above, I normally ask about less frequently used keywords such as yield to asses about candidate’s C# language skills. A normal person who reads theory will start talking like Yield is something we can use with for each statements . But when the next question arrives they will go into mute and the question is “What is the difference in returning a List<T> and using yield return?” .If they had used yield they will say like we can have more than one yield returns but List<T> can be returned once. But is that the only difference?


Some facts about yield
  • Introduced in .Net 2.0 with the intention to make the iteration easier by eliminating use of IEnumerator derived class.
  • Yield can only be used in methods or property get assessors which are returning IEnumerable,IEnumerator or their generic variants.
  • It is not a .Net runtime feature .It is implemented at the language level which will be converted to IEnumerator derived implementation during compilation.ie you can’t see the yield keyword, if you open the assembly in reflector.
  • Usage of each yield keyword adds one compiler generated private class to your assembly.
  • The generated class will have implementation of IEnumerator and most probably you can see a goto statement in its MoveNext method.
  • There is no one to one relation between for…each and yield. ie you can use for…each without yield and yield without for…each
  • Yield depends on IEnumerable but IEnumerable is not depended on yield.
  • There is a usage “yield break” to stop the returns.
  • Yield allows you to write a C# function containing a code path without return statement.
  • VB.Net has got the yield support recently with VB 11 with .Net 4.5
  • Cannot yield return from try {} block if it has a catch block. catch and finally blocks never allows to write yield return.
  • Cannot be used inside anonymous methods or lambda expressions.
I don’t think explanation is needed on each and every item listed above .So let me go over some items.


History of yield keyword
Earlier if we wanted to iterate something we had to implement the IEnumerable interface which will return an IEnumerator for the iteration purpose. IEnumerator interface has some members named Current,MoveNext to achieve the for…each functionality. Look at a sample implementation here .It is little difficult.Isn’t it? This caused the invention of yield keyword which makes the iteration easier.

Dependency
Yield is not a dependency for anything in the C# language. Even if there is no yield keyword we can accomplish all the tasks. But think about IEnumerable. If it is not there for…each and yield cannot exist.


Why goto comes into generated code?
As I told earlier, the yield is not a .net framework /  runtime feature. It’s a C# & VB language feature which will be converted to IEnumerator based equivalent after compilation. This means you cannot expect this keyword in other .Net compatible languages. Sometimes if you look at the generated IEnumerator derived class you can see a goto statement. When it is coming ? Lets take case by case. The below method returns 2 integers using yield.
private IEnumerable<int> GetFirst2Integers()
{
        yield return 0;
        yield return 1;
}



If you open the assembly in reflector you can see a compiler generated private class GetFirst2Integers which implements IEnumerator and the MoveNext method will look as follows.

private bool MoveNext()
{
    switch (this.<>1__state)
    {
        case 0:
            this.<>1__state = -1;
            this.<>2__current = 0;
            this.<>1__state = 1;
            return true;

        case 1:
            this.<>1__state = -1;
            this.<>2__current = 1;
            this.<>1__state = 2;
            return true;

        case 2:
            this.<>1__state = -1;
            break;
    }
    return false;
}
 



No goto statement.Now lets involve a parameter of method into return logic.Say we pass a startFrom parameter.

private IEnumerable<int> Get2Integers(int startFrom)
{
    int i = startFrom;
    while (i < startFrom + 2)
        yield return i++;
}



This produces the MoveNext method with goto.

private bool MoveNext()
{
    switch (this.<>1__state)
    {
        case 0:
            this.<>1__state = -1;
            this.<i>5__a = this.startFrom;
            while (this.<i>5__a < (this.startFrom + 2))
            {
                this.<>2__current = this.<i>5__a++;
                this.<>1__state = 1;
                return true;
            Label_0055:
                this.<>1__state = -1;
            }
            break;

        case 1:
            goto Label_0055;
    }
    return false;
}



I was not able to conclude on what are the exact scenarios which will put goto statement in the generated code. But most of the cases processing the method parameters cause a goto statement.
http://blogs.msdn.com/b/oldnewthing/archive/2008/08/12/8849519.aspx

Returning infinite times
So what are the actual differences .One we saw is the ability for a method to have multiple returns. Another is the ability to return infinite times. For example we can have a method which can yield return the odd numbers infinitely. The process will be stopped only when the for...each iterator stops by break / return keyword.

Delayed return
If the method which returns using yield takes a lot of time to compute the return value ,it is advisable to use IEnumerable with yield as the return value can be processed by the for...each loop before the next value is computed. That doesn't mean we are getting any parallel processing. But a chance to delay the return value generation till the previous value is processed. If the for...each thinks that I am satisfied with the current value ,it can even stop the loop. If we are return as List this is not at all possible. So in this way the yield saves lot of time in the generation method.

Some more links

http://msdn.microsoft.com/en-us/library/9k7k7cf0(v=vs.80).aspx
http://msdn.microsoft.com/en-us/library/hh156729(v=vs.110).aspx

Tuesday, August 16, 2011

Using Generic Type variables as method arguments

Let me start with some theories before a practical scenario. We have base class named MyGenBase inherited from object which accept a generic variable and contains some Properties and there are many derived classes which are not generic.There is also a static method named Process() which needs to accept the base class as it is and manipulate the properties.ie the objects of derived classes will be coming into the Process() as arguments.So how to write the signature of the Process().If we simply use Process(proxy as MyGenBase(of T)) it cannot accept the generic variable  T.If we normally use just T as generic variable it cannot access the variables of MyGenBase.So the solution is to use the generic variable with constraint as follows.

Process(of T)(proxy as MyGenBase(of T)) .

Confused altogether? Sorry I am little bit weak in theory. Lets see a real life example.

Using ClientBase<T> as method arguement

This is about passing a ClientBase<T> type variable as method parameter. ClientBase<T> is a well known class and you might have  used or at least heard, if you have did anything in WCF.

Suppose if we have to add a particular behavior to the proxies which are created at the client side of our application based on some conditions we cannot use the application config files for sure.The only way left is add the behavior through code.For Eg:

Private Function CreateProxy() As IDataService
Dim proxy As new DataServiceProxy
AddMyBehavior(proxy)
Return proxy
End Function
Private Sub AddMyBehavior(ByVal proxy As DataServiceRemoteProxy)
'Somecondition If Then
Dim behavior = New MyBehavior()
proxy.Endpoint.Behaviors.Add(behavior)
' End If
End Sub




Here the DataServiceProxy is the derived class of ClientBase with the generic type as IDataService ie declaration as


Public Class DataServiceRemoteProxy
Inherits System.ServiceModel.ClientBase(Of IDataService)
Implements IDataService
End Class





This is very simple.But if we have more services such as EmployeeService,CustomerService etc…and we need to add the same behavior we need to think about a more generic way of AddMyBehavior.That means we need to accept common base class of DataServiceProxy and EmployeeServiceProxy which is nothing but ClientBase<T> where T may be IDataService or IEmployeeService.If we just use generic variable as T it cannot recognize the EndPoint property which is specific to the ClientBase.Since we don’t have a non generic base class of ClientBase most people uses object as parameter and writes non type safe code or dynamic keyword.

So the question here is how to make the AddMyBehavior to accept any proxy and add the behavior.In the first look it may be complicated and there will be a tendency to pass as object or use the dynamic keyword.But there is a typed way.See the below code snippet.




Friend Shared Sub AddMyBehavior(Of T As Class)(ByVal proxy As ClientBase(Of T))
'Some condition If () Then
Dim cookieBehavior = New MyCookieBehavior()
proxy.Endpoint.Behaviors.Add(cookieBehavior)
'End If
End Sub




Here the ClientBase class accepts only the reference types.That’s why the Class keyword came into play.




Happy Coding!!!

Sunday, July 17, 2011

Goto statement used in .net framework

From the very beginning of the C,C++ and C# days it was told that using goto keyword is not a good practice .Most of the developers are following the same too.They spent little more time in their C# career starting time to avoid goto statements if they are from goto programming world.

But today I happened to see a goto statement not really couple of goto statements in the .net framework. Actually I was searching for a mechanism to parse a string of sql statement and create select command out of that.So obviously I entered in the SQLCommandBuilder class and started reflecting the GetUpdateCommand.After digging into inner methods I saw couple of goto keywords in a private method of DBCommandBuilder.BuildUpdateCommand. Can't you believe? See the below screen shot. I am using .net 3.5.So the framework version shows 2.0.

Is it the problem of reflector disassembling the IL? Or written as it is. Who knows...

Wednesday, August 25, 2010

Applications of Extension methods

Extension methods was introduced some time back with C#3.0 .The feature is great we can attach one more function to the existing classes and can call those methods with the object of those classes itself.It is very helpful for architects to write all the required methods and attach with the existing classes as well.

We all might have surprised by seeing so many methods suddenly in our favorite IEnumerable derived classes such as List and observable collection when the linq is introduced.Did they wrote all these methods inside the List class? absolutely not.Instead they wrote extension methods for IEnumerable and from the user point of view they looks like normal methods because the methods can be invoked  just by using the objects.

I was looking for some uses of the extension methods like this.The option is to replace all most all the helper classes by extension methods. While looking through the helper classes I struck around the reflection helper. The code was written to get the value of property using reflection.If the developer is familiar with the code base he probably knows that there is a helper library and can use it.But what about a fresher.He will surely struck on this and may think about changing the design.If he is coming from the true object oriented world where there is no chance to invoke private properties he is done. The GetProperty and SetProperty really comes helpful here.

Don’t feel so much complicated .Its so simple .Write 2 extension methods which internally gets and sets the value of properties by getting the name of property in string.Now it comes very easy to the end developer as the method will be shown when they type the magic key dot(.)

public static class MyExtensions 
{
    /// <summary>
    /// Gets the value of property mentioned in propertyName.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <param name="propertyName"></param>
    /// <returns></returns>
    public static T GetProperty<T>(this object obj, string propertyName)
    {
        PropertyInfo pi = obj.GetType().GetProperties().FirstOrDefault((p) => string.Equals(p.Name,propertyName));
        T t = default(T);
        if (pi != null && typeof(T) == pi.PropertyType)
        {
            t = (T)pi.GetValue(obj, new object[] { });
        }
        return t;
    }
    /// <summary>
    /// Sets the value of property mentioned in propertyName.Returns true on success.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <param name="propertyName"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool SetProperty<T>(this object obj, string propertyName,T value)
    {
        PropertyInfo pi = obj.GetType().GetProperties().FirstOrDefault((p) => string.Equals(p.Name, propertyName));
        if (pi != null && typeof(T) == pi.PropertyType)
        {
            pi.SetValue(obj,value, new object[] { });
            return true;
        }
        return false;
    }
}

Before using extension methods make sure that the assembly is referred and using the namespace.

SampleVM vm = new SampleVM();
vm.StringProperty = "Joy";
string s = vm.GetProperty<string>("StringProperty");
vm.SetProperty<string>("StringProperty", "Joymon");