In .NET, there is a class called System.Text.Encoding
in mscorlib
. But when you do System.Text.Encoding.ASCII
, you can access the ASCII encoding class.
At first, I thiught this was a class in a class kind of thing:
class Encoding {
class ASCII { ... }
...
}
But what is confusing is that you can also use System.Text.ASCIIEncoding
to access the same functions.
Not being able to decompile .NET (as .NET Reflector costs money and I don't understand IL that well [so no ildasm]), I can't wrap my head around how the two classes are equal. Could it be something like this?
class ASCIIEncoding {
internal ASCIIEncoding() { ... }
/* static functions */
}
static class Encoding {
public static readonly ASCIIEncoding ASCII = new ASCIIEncoding();
...
}
This seems like the most likely way, but the function prototype is
public static Encoding ASCII { get; }
Returning a class deriviated from Encoding
doesn't make sense as Encoding is a class with the Encoding types (ASCII, UTF-(7/8/16/32), etc.), so that means that ASCIIEncoding
would need those variables also, no?
Can anyone help clear up this confusion?
Returning a class deriviated from Encoding doesn't make sense as Encoding is a class with the Encoding types (ASCII, UTF-(7/8/16/32), etc.), so that means that ASCIIEncoding would need those variables also, no?
No, because Encoding.ASCII
etc are static properties, presumably backed by static fields (although that's an implementation detail - the property could just create a new instance each time, or there could be a static internal field within ASCIIEncoding
which it uses, etc).
It's just like this:
public class BaseClass
{
private readonly static BaseClass firstDerived = new FirstDerived();
private readonly static BaseClass secondDerived = new SecondDerived();
public static BaseClass First
{
get { return firstDerived; }
}
public static BaseClass Second
{
get { return secondDerived; }
}
}
public class FirstDerived : BaseClass {}
public class SecondDerived : BaseClass {}
That's complete code - albeit useless in terms of the derived classes actually doing anything. Make sure you understand every bit of how that works, and then just apply it to Encoding
...