There is a WebRequest class, and there is FtpWebRequest.

Instance FtpWebRequest request = new (FtpWebRequest)WebRequest.Create();

I read the Trollsen book in C # and saw such a method only in the example of the explicit implementation of Interfaces (Interface)Class.Method , when the class implements many methods with the same name but from different interfaces, then the call to the specifically inherited method is used to cast to the interface, but in the case With WebRequest, the construction looks like (Class) Class.Method.

I would like to know why, why and how it works?

  • in this case, absolutely for the same: casting an object to type - Grundy
  • The situation is such that there is an abstraction (WebRequest) which implements the method (Create) and its result must be reduced to the final form, but why such complexity? Why can't a descendant class simply implement its create method via override? - BlackOverlord
  • one
    @BlackOverlord in my opinion, WebRequest.Create is one of the holes in .NET design. Those. there was an attempt to make a general approach for working with different protocols, but it did not take off, because Protocols are too different and in practice constantly have to cast. - PashaPash
  • @BlackOverlord, because this is a static method, and they cannot be overloaded - Grundy

1 answer 1

The problem is that, depending on the actual protocol, WebRequest.Create can return HttpWebRequest , FtpWebRequest , and other types. Moreover, it is necessary to find out exactly which type is needed at runtime: after all, you cannot tell the exact address type in it at the compilation stage or Uri ! Therefore, it returns a “generic”, base type.

Now, if hypothetically in .NET were the types of, say, HttpUri and FtpUri , then based on their type, you could create two overloads of the Create function, returning the desired type. (But this would cause a set of problems: in most cases, programmers do not want to know exactly which type of address you have, and they would still use the general type Uri or just a string.)

  • why didn't they do it so that functions from the base class work? polymorphism inheritance, all things? - Grundy
  • one
    @Grundy: But how? What type should the WebRequest.Create(Uri) return? - VladD
  • some basic webrequest for example, well, rather, yes, the desired type is wrapped in a basic one. I understood now that it is impossible to determine which type to create :) - Grundy
  • 2
    If you mean the general, then it happens as you have described. You can work with the returned WebRequest as well. Simply it will not be available ftp-specific chips. - VladD
  • one
    @Grundy: They have not come up with it yet, but the process is going on :) - VladD