3

I am learning C# and I am a beginner. I wanted to request a URL for a hardware project (raspberry pi server controlling curtains) It works but I don't understand this line below:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(rpiIp.text);

I don't understand what the "(HttpWebRequest)" bit is for and how it affects the "WebRequest.Create();" Method.

Can someone explain?

Thanks a lot James

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
James
  • 156
  • 7
  • 1
    `WebRequest().Create()` returns an object of type `WebRequest` (which is an **abstract** class - a base class for others, that cannot be instantiated on its own, really). However, if you need to use properties and methods that are defined on the descendant class, like `HttpWebRequest`, you must **type-cast** the return type to the concrete, derived class that you need/want – marc_s Jul 12 '14 at 16:37
  • The **(HttpWebRequest)** is called a cast, and is an instruction to the compiler to both ensure that the assignment RHS is valid as an instance of this type, and to only allow assignment to a LHS of this type. – Pieter Geerkens Jul 12 '14 at 16:38
  • What language is the RPi server written in? – Austin Mullins Jul 12 '14 at 17:23
  • Python, using flask library and GPIO library. I hate python but I can't be bothered with c socket programming for the far superior C gpio library – James Sep 11 '15 at 20:14

1 Answers1

4

It is called an Explicit Cast. From MSDN:

Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class

The method WebRequest.Create returns an object of type WebRequest, which is an abstract class, meaning an instance of it cannot be created, only an underlying derived type which inherits from WebRequest. What the cast is doing in this case is telling the compiler: "Listen, i know Create actually returns an HttpWebRequest from this method, so let me treat it like one". When the cast is being done, it will either succeed if the actual type is a HttpWebRequest or it will throw an InvalidCastException if it isn`t

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • It is probably helpful to point out that an Explicit Cast differs from an Implicit Cast. See this post from another C# beginner: http://stackoverflow.com/questions/1176641/explicit-and-implicit-c-sharp/1176680#1176680 – Philip Pittle Jul 13 '14 at 22:40