What is a class? - c#

I can imagine the first reaction when you read the title of my question: "How can you have such a high reputation here and ignore what a class is?"
My point is the following: until now I have always worked with C++, Delphi, Java, ... and there it's quite simple: a class is a type definition of an object. You need to reserve some space in memory to start using it (hence the constructor) and afterwards, don't forget to free that memory (if your programming language does not support garbage collection).
Today, however, I had a problem concerning type definitions and constants in C#, and I fell on this URL, mentioning such pieces of source code:
class Calendar1
{
public const int Months = 12;
}
In order to use this, you just need to do:
using Calendar1;
And you can use Months as a constant.
But here's my question: where's the constructor? If this class is the type definition of an object, which object are we talking about?
So, if I understand correctly, C# is based on the idea "Everything is a class", but in order to make this work, the C# inventors have extended the definition of a class, so now we get (C# definition):
A class is one of the following:
a type definition for an object. In that case, a constructor is needed for creating the object.
...
Can somebody finish the definition?

This is a pretty common practice in C#. Classes are often used to create "sacks" to hold constants, or commonly as a entity or dto object. These are usually made without a user defined constructor. If a class does not have a constructor, one is defined at compile time which amounts to an empty constructor:
public Calendar1()
{
}
This answer goes into much further detail:
C# class without constructor

You don't need this using. using is to make namespaces available.
A constant is static. This means that it is not an instance member but a member of the type. Thus, you can access it through the type name: Calendar1.Months or, with a using static Calendar1; just with Months.
In C# a class implicitly creates a parameterless public constructor, if you don't declare one explicitly.

When you are creating a instance of a class you are allocating memory (using the keyword new)
Constants are created not in runtime, they are created in compile time and stored in the assembly metadata. So when you are accessing a constant you will be not accessing an instance of a class - you will be accessing the constant from the metadata directly.
Have a look at this post:
How are C# const members allocated in memory?

Related

Why a constructor should be in the class scope?

A Constructor is used to instantiate(allocate memory) for an object. Yet if I write a class like this:
class Sample
{
int a=10,b=20;
}
In above example what is the purpose of Constructor? I am assigning values to variables anyway, ts Constructor compulsory in every case?
Initialization of values of different variables is critical in any application development. C# does initialize simple data-types to default values as per the language specification in the .Net framework, but for classes that are user specific, it is obvious that you would be the only one who can decide what is an ideal default value. The means of achieving this is Constructors. There is also a perception that constructors can only be used beyond initialization, which is true to some extent.
Reference :
http://www.c-sharpcorner.com/UploadFile/vishnuprasad2005/HowuseCSharpConstructors11302005015338AM/HowuseCSharpConstructors.aspx
http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html

About the dot (.) operator of c#

Sorry about the last post...here is another one.
So far I've seem people use the (.) operator to :
(1) access member of structure
(2) access static/constant member of a class
(3) access literal of a enum-type
(for example, those of dayofweek.cs http://referencesource.microsoft.com/#mscorlib/system/dayofweek.cs)
without having object/instance of that structure/class/enum .
I know that an operator's meaning can depend on its operand;
but some of them looks kind of weird to me.
For example, in the case of (3):
In C#, I can write:
DayOfWeek a;
if (a == DayOfWeek.Sunday) *do something...*;
but in C, I can only write:
DayOfWeek a;
if (a == Sunday) *do something...*.
For another example, in the case of (1):
In C, only after we have an instance of a structure can we do operation to its member;
but in C#, just like in https://stackoverflow.com/questions/24888864/two-things-about-source-code-of-struct-datatime-in-c-sharp, we can directly use NAME(i.e., DataTime) of a structure to access its member(i.e., Maxticks), i.e.,DataTime.Maxticks
There obviously is some difference, right?
Where can I read the thorough tutorial or doc of this operation, saying what how I can use this operation? Only the language spec?
**I actually don't appreciate the way learning that by looking through examples using this operation one-by-one, because they don't tell me "how to use it", but just "what I can do with it"; these two are different, though.
As you have noticed, the . operator is used to access a member.
If that member is marked static, then you can reference it via class name, since there is only ever one static "instance" of a class (and it is instantiated by the runtime). That is what your are seeing with DateTime.MaxTicks.
Enums are not static but their members are accessed the same way, because you need to qualify the member name with the enum name. From the C# spec (v 5.0, section 14.3):
From all other code, the name of an enum member must be qualified with
the name of its enum type. Enum members do not have any declared
accessibility—an enum member is accessible if its containing enum type
is accessible.
One of the uses of . is to qualify something (like when you explicitly declare which namespace a class is coming out of).
Basically, you use . whenever you want to access a member of something. As long as you know if it is an instance or static variable, you'll know if you need an instance of the type or if you can just use the class name. . can also be used to qualify the name of something, which is used when specifying a namespace for a class or using an enum.
In C, only after we have an instance of a structure can we do
operation to its member;
but in C#, just like in Two things about source code of struct
DataTime in c#, we can directly use NAME(i.e., DataTime) of a
structure to access its member(i.e., Maxticks), i.e.,DataTime.Maxticks
There obviously is some difference, right?
We can use the name of class and then dot and the method we want to call, when the method of the class is a static method. In this case the method belongs to the class and not to the objects we create using the new keyword.
From the C# specification:
A method is a member that implements a computation or action that can
be performed by an object or class. Static methods are accessed
through the class. Instance methods are accessed through instances of
the class.
One of the best explanations about the static keyword can be found in MSDN.
As for the access of the members of a struct in C#, you use the same operator you use to access the members of a class in C#, the dot operator. This is the reason, why you need DayOfWeek.Sunday.
Think of it as navigating the namespace. Your project structure could be:
MyApp
Forms
MainForm
ShowForm()
IsOpen()
Classes
SomeClass
SomeStaticMethod()
NonStaticMethod()
OtherClass
SomeEnum
EnumValueOne
EnumValueTwo
Repositories
ThisRepo
All of this would be called, imported, or accessed a similar way using dot notation despite their different purposes and structures. Calling the static ShowForm() void on MainForm would be MyApp.Forms.MainForm.ShowForm(), just like referencing an enum in OtherClass would be done like MyApp.Classes.OtherClass.SomeEnum.EnumValueTwo.
You obviously won't need to do the full qualifying namespace when you add a using statement to your class, but hopefully this shows the concept.

Are static members of a generic class tied to the specific instance?

This is more of a documentation than a real question. This does not seem to have been addressed on SO yet (unless I missed it), so here goes:
Imagine a generic class that contains a static member:
class Foo<T> {
public static int member;
}
Is there a new instance of the member for each specific class, or is there only a single instance for all Foo-type classes?
It can easily be verified by code like this:
Foo<int>.member = 1;
Foo<string>.member = 2;
Console.WriteLine (Foo<int>.member);
What is the result, and where is this behavior documented?
A static field is shared across all instances of the same type. Foo<int> and Foo<string> are two different types. This can be proven by the following line of code:
// this prints "False"
Console.WriteLine(typeof(Foo<int>) == typeof(Foo<string>));
As for where this is documented, the following is found in section 1.6.5 Fields of the C# Language Specification (for C# 3):
A static field identifies exactly one
storage location. No matter how many
instances of a class are created,
there is only ever one copy of a
static field.
As stated before; Foo<int> and Foo<string> are not the same class; they are two different classes constructed from the same generic class. How this happens is outlined in section 4.4 of the above mentioned document:
A generic type declaration, by itself,
denotes an unbound generic type that
is used as a “blueprint” to form many
different types, by way of applying
type arguments.
The problem here is actually the fact that "generic classes" are not classes at all.
Generic class definitions are just templates for classes, and until their type parameters are specified, they are just a piece of text (or a handful of bytes).
At runtime, one can specify a type parameter for the template, thus bringing it to life, and creating a class of the, now, fully specified type. That's why static properties are not template-wide, and that's why you cannot cast between List<string> and List<int>.
That relationship kinda mirrors the class-object relationship. Just like classes do not exist* until you instantiate an object from them, generic classes do not exist, until you make a class based on the template.
P.S. It's quite possible to declare
class Foo<T> {
public static T Member;
}
From this is kinda obvious that the static members cannot be shared, as T is different for different specializations.
They are not shared. Not sure where it's documented but analysis warning CA1000 (Do not declare static members on generic types) warns against just this due to the risk of making the code more complicated.
C# implementation of generics is more closer to C++. In both of these languages MyClass<Foo> and MyClass<Bar> don't share static members but in Java they do. In C# and C++ MyClass<Foo> internally creates entirely new type at compile time as if generics are kind of macros. You can usually see their generated names in stack trace, like MyClass'1 and MyClass'2. This is why they don't share static variables. In Java, generics are implemented by more simpler method of compiler generating code using non-generic types and adding type casts all over. So MyClass<Foo> and MyClass<Bar> don't generate two entirely new class in Java, instead they both are same class MyClass underneath and that's why they share static variables.
They are not really shared.
Because the member doesn't belong to the instance at all.
A static class member belongs to the class itself.
So, if you have MyClass.Number it is the same for all MyClass.Number objects because it not even depends on the object.
You can even call or modify MyClass.Number without any object.
But since Foo< int > is not the same class as Foo< string > these two numbers are not shared.
An example to show this:
TestClass<string>.Number = 5;
TestClass<int>.Number = 3;
Console.WriteLine(TestClass<string>.Number); //prints 5
Console.WriteLine(TestClass<int>.Number); //prints 3
IMO, you need to test it, but I think that
Foo<int>.member = 1;
Foo<string>.member = 2;
Console.WriteLine (Foo<int>.member);
will output 1 because I think that, during compilation, the compilator create 1 class for every generic class you use (in you example : Foo<int> and Foo<string>).
But I'm not 100% sure =).
Remark : I think it's not a good design nor a good practice to use such kind of static attributes.

Why are static classes considered “classes” and “reference types”?

I’ve been pondering about the C# and CIL type system today and I’ve started to wonder why static classes are considered classes. There are many ways in which they are not really classes:
A “normal” class can contain non-static members, a static class can’t. In this respect, a class is more similar to a struct than it is to a static class, and yet structs have a separate name.
You can have a reference to an instance of a “normal” class, but not a static class (despite it being considered a “reference type”). In this respect, a class is more similar to an interface than it is to a static class, and yet interfaces have a separate name.
The name of a static class can never be used in any place where a type name would normally fit: you can’t declare a variable of this type, you can’t use it as a base type, and you can’t use it as a generic type parameter. In this respect, static classes are somewhat more like namespaces.
A “normal” class can implement interfaces. Once again, that makes classes more similar to structs than to static classes.
A “normal” class can inherit from another class.
It is also bizarre that static classes are considered to derive from System.Object. Although this allows them to “inherit” the static methods Equals and ReferenceEquals, the purpose of that inheritance is questionable as you would call those methods on object anyway. C# even allows you to specify that useless inheritance explicitly on static classes, but not on interfaces or structs, where the implicit derivation from object and System.ValueType, respectively, actually has a purpose.
Regarding the subset-of-features argument: Static classes have a subset of the features of classes, but they also have a subset of the features of structs. All of the things that make a class distinct from the other kinds of type, do not seem to apply to static classes.
Regarding the typeof argument: Making a static class into a new and different kind of type does not preclude it from being used in typeof.
Given the sheer oddity of static classes, and the scarcity of similarities between them and “normal” classes, shouldn’t they have been made into a separate kind of type instead of a special kind of class?
It's a class as far as the CLR is concerned. It's just syntactic sugar in the C# compiler, basically.
I don't think there would be any benefit in adding a different name here - they behave mostly like classes which just have static methods and can't be constructed, which is usually the kind of class which became a static class when we moved from C# 1 to C# 2.
Bear in mind that if you want to create a new name for it, that probably means a new keyword too...
Your question is "why do I have to type the words static class X rather than foobar X". The answer is, because programmers already associate the word 'class' with 'a bundle of tightly packed encapsulated functionality someone wrote for me'. Which, coincidentally, fits perfectly with the definition of static classes.
They could've used namespaces instead, yes. That's what happens in C++. But the term 'static class' has an advantage here: it implies a smaller and much more tightly coupled group of functionality. For example, you can have a namespace called Qt or boost::asio but a static class called StringUtils or KWindowSystem (to borrow one from KDE).
Yes, they are very odd. They do have some class-like behavior, like being able to have (static) member variables, and restricting access to members using public/private.
I almost typed "public/protected/private" there, but obviously protected doesn't make sense, because there is no method inheritance of static classes. I think the main reason for this is that because there are no instances, you can't have polymorphism, but that is not really the only reason for inheritance. Polymorphism is great, but sometimes you just want to borrow most of the functionality of the base class and add a few things of your own. Because of this, sometimes you'll see static classes switched to use singleton patterns, just so that it can leverage the some functions from base set of classes. In my opinion this is a hacky attempt to close that gap, and it gets confusing and introduces a lot of unnatural complexity. The other option is aggregation, where the child class methods just pass calls through to the parent class methods, but this is requires a lot of code to stich it all together and isn't really a perfect solution either.
These days, static classes are usually just used as a replacement for global methods, i.e. methods that just provide functionality without being bound to an instance of anything. The OO purists hate any concept of a free/global anything floating around, but you also don't want to have to have an unnecessary instance and object floating around if you just need functionality, so a static "class" provides a middle-ground compromise that both sides can sort of agree with.
So yes, static classes are weird. Ideally, it would be nice if they could be broken into their own concept that provided the flexibility and lightweight ease-of-use that you get from methods that don't need to be bound to an instance (which we have now with static classes), and also group those methods into containers (which we also have now), but also provide the ability to define a base entity from which it will inherit methods (this is the part that is missing now). Also, it would be great it was a seperate concept from classes, for exactly the reasons you raise, it just gets confusing because people naturally expect classes to be instances with properties and methods that can be created and destroyed.
I don't know if this qualifies as an answer, but I would point out that "static classes" are more of a language concept and less of a CLR concept. From the point of view of the CLR, they are just classes, like any other. It's up to the language to enforce all the rules you described.
As such, one advantage of the current implementation is that it does not add further complexity to the CLR, which all CLR-targeting languages would have to understand and model.
Sure, they could have been made into a separate kind of thing.
But that would have required additional work in the CLR, the BCL, and across the language teams, and I that would have left other, more important things undone.
From a purely aesthetic point of view, I might agree with you.
Good point, it's probably because of historic reasons, i.e. they didn't want to invent something new as static classes already existed.
C++, Pascal (Delphi) and Java all have static classes, and those are what C# is based on.
Static classes and "normal" classes (and structs) are containers for executable code (members fields, properties, methods) and they declare a Type. If they had a separate word for this then we would ask the opposite ("if they are so similar, why did you not use the kayword class?").
I'd suggest "CLR via C#", where it's well explained how type resolving, method calling, etc occurs. It works in the same way for "both" classes, just instance members have additional parameter passed in for the instance object.
Classes are not like namespaces because they are only for naming and referencing. They do not affect the functionality of the class.
Classes are also different from interfaces, because interfaces are merely compile-time verification tools and do not have functionality of their own.
In my opinion, static classes are considered so because they can embed private fields, public properties and methods, though they are static, and have a fixed address location where each call to the singleton method or property will have its reference.
A structure is more likely a value type as when you write:
var struct1 = new Struct1();
var struct2 = struct1;
each of the properties will have been copied into a new memory location. Furthermore, with a structure, you will be able to change struct2.Property1 value without having it changed within struct1.Property1.
Per opposition, classes are in my understanding reference types, as when you write:
var class1 = new Class1();
var class2 = class1;
Here, the reference is copied. This means that when you change class2.Property1, this same property will also change in class1.Property1. This is because both classes points to the same memory address.
As for static classes, they are considered as reference types as when you change a StaticClass.Property value within a method, this change will get populated everywhere you reference this class. It has only one memory address and can't be copied, so that when another method or property call will occur, this new value will prevail over the old one. Static classes are meant to be shareable accross an entire application, so only one reference for it exists within your application. Therefore making them behave like a class.
A static class, even though singleton pattern is not, I guess, encouraged except for absolute purpose, could represent a real-life object just like a class or an instance of a class. However, since unique-in-the-world-objects seem to be rare enough, we don't really need them to represent a practical object, but merely some logical ones instead, such as tools and so forth, or some other costy-to-instiate objects.
EDIT
In fact, a static class is so similar to a class that in Visual Basic, there is no static class, but only a class with static (Shared in Visual Basic) members. The only point to consider is to make this class NotInheritable (sealed in C#). So, C# provides a more implicit functionality by allowing to declare a class static, instead of making it sealed, with an empty default constructor, etc. This is some kind of a shortcut, or syntaxic sugar, like we like to say.
In conclusion, I don't think there would be any benefit or gain having a new keyword for it.
Although class types, value types, and interfaces behave in many regards as though they are in three different kinds of things, they are in fact all described using the same kind of Type object; the parentage of a type determines which kind of thing it is. In particular, all types in .NET are class types except for the following:
Types other than System.Object which inherit from null; those are interfaces.
Types other than System.ValueType or System.Enum which inherit from System.ValueType or System.Enum; those are value types.
A few types like pointers and byrefs, which may be identified by Type objects (necessary for things like parameter types) but don't have members the way other types do.
Every type which has members, and whose parentage does not meet either of the above criteria, is considered to be a class. Static classes aren't really classes because of any particular quality they have, but rather because they don't have any quality that would make them be some other named kind of thing, and calling them "static classes" seems easier than inventing some other term to describe them.
What about static constructors? I think this is another important aspect to consider in your comparison. Classes and structs support them but interfaces and namespaces do not.
Construction implies instantiation. While the implementation may not actually create an "instance" of a static class, you could view static classes as a singleton instance of a class, to which there can only ever be one reference (the typename itself). If you could inherit static classes, you would break the singleton notion. If you could declare variables of the type, you might expect them to be cleaned up by the garbage collector when they are no longer referenced.
Why are they classes instead of structs? When I think of structs (value types), I think about values on the stack. Their existence is (typically) very short and they are copied frequently. This again breaks the single reference singleton notion above.

What is the use of a static class

What is the use of a static class?
I mean what are benefits of using static class and how CLR deals with static classes?
A static class simply denotes that you don't expect or need an instance. This is useful for utility logic, where the code is not object-specific. For example, extension methods can only be written in a static class.
Pre C# 2.0, you could just have a regular class with a private constructor; but static makes it formal that you can never have an instance (there is no constructor*, and all members must be static).
(*=see comment chain; you can optionally have a type initializer (static constructor aka .cctor), but you cannot have an instance constructor (aka .ctor)).
The compilation and metadata model for .net requires that all functions are defined within a class. This makes life somewhat easier and simpler for the reflection api's since the concepts of the owning class and its visibility is well defined. It also makes the il model simpler.
since this precludes free functions (ones not associated with a class) this makes the choice of where to put functions which have no associated state (and thus need for an instance). If they need no state associated with them nor have any clear instance based class to which they can be associated and thus defined within there needs to be some idiom for their definition.
Previously the best way was to define the methods within a class whose constructor was private and have none of the functions within the class construct it.
This is a little messy (since it doesn't make it crystal clear why it was done without comments) and the reflection api can still find the constructor and invoke it.
Thus static classes were allowed, making the intent of the class, that of a place for the definition of static methods, clear to users and to the type system. Static classes have no constructor at all.
A static class is a language hack to write procedural programs in C#.
All members of a static class has to be static members, so, if you forget to add 'static' before any of them your code won't compile, it also makes your code more readable as anyone who will see that the class is static will understand it only contains static members.
The best use for a static class is for utility functions, you could also use them to keep the global methods and data in your application, I use static static classes very often in almost any project.
Static classes are often used to group related global services which you initially don't want to be accessed with an object instance. An example is the Math class in the .Net BCL, which you use directly, e.g., Math.Sqrt(10.0)
Static classes are sealed. This may be a useful option to use static for utility classes.
I got clear idea from this statements.
To know more about static class. First we must differentiate between static and instance data first.
Each time you create a new instance of a class you get a new copy of the instance data to play with. The instance methods of the class work on the instance data. The instance data is completely independent of the instance data in all other classes and even instances of the same class. If you change a value in one instance it has no impact on the same value in other instances. The bulk of program data is instance data.
Static data is equivalent to global data. Everybody in the program sees the same data. If someone changes the data then everybody else will see the change as well. Static data is useful for sharing information across a program such as database connection strings or log files. There is only one copy of static data in memory in general. (There are exceptions such as when dealing with multiple appdomains).
When you create an instance of a class you are effectively allocating some memory to hold your own copy of the instance data defined by the class. If you create 5 instances of a class then you get 5 separate memory locations where each location has its own copy of the instance data. Each memory block is independent of the others.
If a class has no instance data then it doesn't make any sense to create instances of it. Doing so is harmless but also a waste of time. This is where static classes come in. A static class is a way to identify a class as having no instance data. By marking the class as static you are telling the compiler that all the data in the class is shared across the board. As a result the compiler enforces some rules to make things clear. A static class can only contain static members. A static class cannot be instantiated. A static class must be sealed. The compiler enforces this for convenience of the developers.
A static class is sealed. This is because static classes cannot have per-instance data.
Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static constructor is called once and the static class remains in the memory for the lifetime of the application domain in which your program resides.
Reference: http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx
1.First of all u cannot create the instance for static classes
If the class declared as static, member variable should be static for that class
3.Sealed [Cannot be Inherited]
4.Cannot contains Instance constructor
5.Memory Management
Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]
In a class we declare a function as static,only if that function is not associated to any objects. We should not use "this" operator in that static function, because "this" operator will refers to object which invoke the function. Eg: Consider a class named Employee has few variables like Name, Age, Department, in this Employee class i am going to add a function called getSimilarNames() that will show How many employees having similar names. This function need not to be associated to any Employees. So I declare this function as a Static.If a class that only contains static functions, we declare that class is a static class. The Static function improves performance.

Categories