I have learnt so far that abstract classes can’t be instantiated because they are only there for other classes to inherit from. But i cant get my head around this code i came across in the msdn library:
WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
in the documentation it says the above code returns a WebRequest instance.
but the WebRequest class is an abstract class, and how comes the above code returns an instance of an abstract class when abstract classes can’t be instantiated.
please relieve me from my agony.
2
Most likely, the Create
method in that example will return an instance of a subclass of WebRequest
.
To see exactly what you’re getting back, you could try something like this:
WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
Type t = myRequest.GetType();
Console.WriteLine(t.Name);
1
Abstract classes can’t be instantiated immediately. That is, you can’t do new SomeAbstractClass()
. However, you can instantiate subclasses of an abstract class. So abstract classes are similar in function to interfaces, except that they can contain method definitions and member fields.
As such, abstract classes are great for introducing a level of abstraction. The WebRequest
class is a good example here: It has subclasses for various protocols such as HTTP or HTTPS. When you instantiate a request via WebRequest.Create("https://example.com/")
, you get a web request instance that can handle the HTTPS protocol, but is also a WebRequest
instance. The static method Create(…)
is a factory method.
See also the documentation for WebRequest.Create(…)
1
WebRequest
is an abstract class that can’t be instantiated. WebRequest.Create
is a static method that returns a concrete type of System.Net.HttpWebRequest
that is a derived subclass of System.Net.WebRequest
. Because it is a derived type, it still identifies itself as a WebRequest
even though it’s fully qualified type name is System.Net.HttpWebRequest
.
The reason this is useful is that you no longer need to care about the actual implementation. You know that a WebRequest
will have all of the functionality you need so if the concrete type is a System.Net.HttpWebRequest
or a Steves.Awesome.WebRequest
or a Georges.NotSoAwesome.WebRequest
it doesn’t matter because they’re all inherited from WebRequest
.
Your line of code:
WebRequest myRequest = WebRequest.Create("http://www.contoso.com");
This isn’t saying that it’s actually going to create a WebRequest
and only a WebRequest
. It’s saying that whatever is created will inherit from WebRequest
and be compatible with anything you need going forward from the standpoint.