views:

151

answers:

1

Hello

This is a VB.Net newbie question. I'm confused at the different ways to declare and define variables.

Here's an example:

Dim URL As String = http://www.c-sharpcorner.com/default.asp
Dim request As HttpWebRequest = WebRequest.Create(URL)
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As StreamReader = New StreamReader(response.GetResponseStream())

When should I use 1. nothing, 2. call the Create() method, 3. Call another method of the object besides Create(), and 4. use the New word?

Thank you for any tip.

A: 

Most primitive types (Int32, String etc) in .Net have a literal syntax that allows to you declare a new instance. Where this is available, it should probably be your first choice. Your URL variable from above would be an example of this.

Your next choice would probably be the New keyword. This is good where the type that you are trying to instantiate is known at design time. This might not be appropriate for example if you are just trying to instantiate an instance of a type that implements an interface but do not care about the concrete type of the object that is returned.

A design pattern that you can use in this case (the type is not known at design time) is the Factory Method. The way that the Factory Method is initialized, can influence the type of the object that it returns.

If a class does not have an externally visible constructor then it is probably because the developer of that class wanted to reserve the right to decide at runtime which type he will return. In this case, he will generally provide a Factory Method (prefixed with the Create keyword by convention). The method will not necessarily be on the class that you are trying to instantiate but might be added to some other class in the API that has the context required to firstly make the decision as to which concrete class to return and secondly has the ability to provide the necessary dependencies to create the object.

In summary your decision path should probably be..

  1. Literal
  2. Constructor
  3. Factory Method

As an interesting aside - the DateTime data type is a case where VB.Net has a literal syntax and C# does not. The 31st of May 1999 can be instantiated as a DateTime object in VB.Net using the syntax #5/31/1993#. To instantiate the same date value in C# would require the use of the constructor new DateTime(1999, 5, 31).

Scott Munro