Answer the question
In order to leave comments, you need to log in
Understand the c# language (and OOP in general, I guess)?
Greetings.
There is a class (A) and a public class nested inside it (B).
Why (?) can we declare an instance object of a nested class (B) like this:
new AB()
Class B is not static.
And why (?) can't we define it like this:
A a = new A();
new aB();
The behavior is as if class B is static, but it is not.
I can just put up with it, but I want to understand to the end why this is happening.
And one more follow-up question.
What are static classes for? You can't inherit or create objects.
Is it an exotic alternative to namespaces? What can be done with them?
And one more question:
Is the "as" operation equivalent to type casting through parentheses before an object?
Thank you.
Answer the question
In order to leave comments, you need to log in
Why (?) can we declare an instance object of a nested class (B) like this:
new AB()
Class B is not static.
And why (?) can't we define it like this:
A a = new A();
new aB();
public static class MyExtensionProvider
{
public static void DoSomething(this Object targetObject)
{
return;
}
}
I'm afraid all this does not apply to OOP. Static classes and nested classes are a holdover from other concepts, but not OOP.
Class B is a "property" of class A, not instances of that class. This is just logically - the class is a declarative entity, metadata is used at the compilation stage, and not at runtime. And C# is a static language.
Static classes are needed to combine global objects/functions. In particular, they are often used to create utility classes (for example, for some tricky printing of a list of something).
The as operator is not quite equivalent to parenthesis casting.
If the cast fails, the option with brackets will throw an exception.
Whereas the option with as will simply return null
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question