C# Language question for a guru
-
WebRequest wrGETURL; wrGETURL = WebRequest.Create(sURL); ((HttpWebRequest)wrGETURL).UserAgent = "Mozilla/5.0"; Q1) On the first line above we can see that WebRequest is a class. On line 2 it seems to me that WebRequest is now an "instance". Could somebody explain that to me? I don't understand how you can call a method on a "class". I thought you had to call it on an "instance of the class". Q2) In the third line wrGETURL is being cast to HttpWebRequest. I really don't understand how this could be legal since HttpWebRequest is derived from WebRequest. Could somebody demonstrate this casting using a generic set of classes (foo, bar ... etc.) Thanks!
-
WebRequest wrGETURL; wrGETURL = WebRequest.Create(sURL); ((HttpWebRequest)wrGETURL).UserAgent = "Mozilla/5.0"; Q1) On the first line above we can see that WebRequest is a class. On line 2 it seems to me that WebRequest is now an "instance". Could somebody explain that to me? I don't understand how you can call a method on a "class". I thought you had to call it on an "instance of the class". Q2) In the third line wrGETURL is being cast to HttpWebRequest. I really don't understand how this could be legal since HttpWebRequest is derived from WebRequest. Could somebody demonstrate this casting using a generic set of classes (foo, bar ... etc.) Thanks!
A1) In the second line, WebRequest is still a class, and Create() is a static[^] method of that class. A2) Well, WebRequest.Create() can return various types of web requests (including HTTPWebRequest), therefore, it needs to have the generic web request as a return type. In this case, I suppose that the URL is assumed to start with "http://" and therefore return an HTTP request.
"Blessed are the peacemakers, for they shall be called sons of God." - Jesus
"You must be the change you wish to see in the world." - Mahatma Gandhi