Dot Net For All

Curious case of typeof in C# and VB.NET

Hello friends, If you are a poor soul like me who works on the multiple programming languages like VB.NET, C# to name a few. This article can be of some help to you. And if you are luck enough to be master of one language you can get some insights about the two popular .NET programming language.

In this article one of the operator keyword which every .NET developer encounters named as typeof. But the purpose it servers in both of the languages is different.

If you are the curious one to know how C# and vb.net treats typeof, continue reading the article.

typeof in C#

Lets start with typeof operator keyword utilization and use in C#.

typeof is used to get the type of any object at compile time or it returns the System.Type object. But you must be wondering why do we need to get the type of any object. This can be helpful in many scenarios. Couple of which I can think of now are following.

If you are creating a DataTable at run time in the code. And if you want to add the columns to the datatable you need to provide the type of the column as seen in the code below.

            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(String));
            dt.Columns.Add("Age", typeof(Int32));

Though the above code can be written without providing Type parameter. But that would not be same and any user of the DataTable can be in trouble by not knowing the type of the columns added.

One another example of the use of typeOf keyword in C# I can think of is if we want to convert the response payload of a web api request to C# compatible type.

            HttpClient client = new HttpClient();
            var values = new Dictionary<string, string>
                            {
                               { "thing1", "hello" },
                               { "thing2", "world" }
                            };

            var content = new FormUrlEncodedContent(values);
            var response = client.PostAsync("http://www.example.com/Hello", content);
            var responseString = response.Result.Content.ReadAsStringAsync();

            HelloWorld message = (HelloWorld)Newtonsoft.Json.JsonConvert.DeserializeObject(responseString.Result, typeof(HelloWorld));

In the above C# code example, I am calling an imaginary web URL with the POST method and I am expecting a data in the response.

The imaginary data I am expecting is of below type in json format.

        class HelloWorld
        {
            public string Message { get; set; }
        }

And that is why I am using typeof keyword to provide the compile time type of the class.

typeof in VB.NET

Ah and there is typeof keyword operator in VB.NET as well. But its not the same as C# operator.

In VB.NET it is used to verify the type of reference type at run-time and returns a Boolean value.

An example of the same in the below code

   Sub Main()

        Dim myClassIns As MyTestClass = New MyTestClass()
        Dim isClass As Boolean = TypeOf myClassIns Is MyTestClass

        Console.WriteLine(isClass)
        Console.Read()

    End Sub

Public Class MyTestClass

End Class

The above code returns true as I am using the instance of the MyTestClass.

I am not sure why the same keyword in has two utilization in .NET framework. But it can be confusing.

It could have been done the same way as done in C#. Just by using the “Is” keyword operator.

 typeOf Alternative in VB.NET

But what if we want to know the type of an object reference at compile time in VB.NET.

We can use GetType keyword operator in VB.NET and it serves the same purpose as typeof in C#.

Please have a look at the below code DataTable VB.NET code which I have written above

        Dim dt As DataTable = New DataTable()
        dt.Columns.Add("Name", GetType(String))
        dt.Columns.Add("Age", GetType(Int32))

And we are good with it.

Conclusion:

Working with different programming languages can be difficult and rewarding at the same time. But we need to understand the subtle differences. As we did in this article to understand the different use of typeof keyword operator in C# and VB.NET.  Finally the C# typeOf Alternative in VB.NET .

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview