Query regarding static class in c# - c#

Hi all I just wanted to know whether a static class which inherits another class, can have access to the parent classe's non static members or not?
Please help. Thanks in advance.

A static class cannot inherit or implement any class or interface.
The point of inheriting or implementing a class or interface is to allow instances of your class to be used as the base type.
Since static classes cannot have instances, there's no point.

How should that work? A static class cannot be instantiated and therefor it will never have access to any non static members.

A static class is basically the same
as a non-static class, but there is
one difference: a static class cannot
be instantiated. In other words, you
cannot use the new keyword to create a
variable of the class type
You can view more information about static classes.

static class cannot inherited .
I think you can go with the same concept with SingleTon class and you can inherit the same.

A static class can't inherit from any classes or implement any interfaces.
A static class does implicitly inherit from Object, though. But since it's (also implicitly) abstract you can never have any instances of it, and so can never call any instance methods in Object. Also, it's (implicitly) sealed, and as such cannot have subclasses that would be instantiatable. As a corollary to these characteristics, it can't be used to type any variables, fields or parameters; and it can't be used as a type parameter (if these were possible, null would be the only valid value for such references).
Given all this, a static class does not look like a class at all, and I think would be better represented as a module.

Related

Do C# classes default to instance or static classes if not specified?

When declaring a class in C# without specifying if the class is a static or non-static class which will it default to?
EDIT: Here's an article I wrote based on this discussion.
https://hackernoon.com/c-static-vs-instance-classes-and-methods-50fe8987b231
If you don't declare the class as static then its members can be either static or non-static.
A static class can only have static members.
You can invoke non-static members only on instances of the class.
You can invoke static members only on the class itself.
Also, in your class declaration, there are no parentheses.
If the "static" is not specified, it will require an instance of the class to be used (Unless the member itself is specified as static).
If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable.
From: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes
A class is always an instance class unless you specify otherwise

What are the ways to declare a class that cannot be instantiated?

What are the ways to create a non-instantiable class? One way is by declaring it as an abstract class. Is it possible to do it by making the class constructor as private? Is a sealed class, non-instantiable? And, are there any other ways to do it in C#?
Marking a class as abstract or static (they are mutually exclusive) are the only two ways. Marking all constructors as private does not make the class uninstantiateable since the class can still construct itself, and others might be able to do it via reflection.
Only static looks like complete solution here because abstract class still can be instantiated when class instance that inherits from it is instantiated. Consider the scenario :
abstract class A { }
class B : A { }
somewhere in code :
B instance = new B(); // this creates instance of class A as well
P.S.
At first i though that abstract sealed might be solution for this problem as well but it doesn't make much sense to use such a construction so it doesn't even compile :
Error 1 'A': an abstract class cannot be sealed or static D:\Projects\TEST\Testapp\Program.cs 15 27 ITT.Domain
As answered by others abstract and static classes cannot be instantiated however a class with private constructor can be by using a public member function. This is how the singleton pattern works
internal classes are only visible inside of your assembly and therefore cannot be instantiated outside of this assembly.
But as far as i know, you could still create an instance via reflection.
you can disable reflection via ReflectionPermission Class
As mentioned above you could declare it as abstract or add an abstract method.
If you just want to declare a contract, you could use an interface, but that's not a class at all.
sealed means you cannot inherit this class
singleton classes can only be created once per application
singleton
see sealed (C# reference)

Abstract classes vs Static classes in C# [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the difference between an abstract class and a static one?
Hello
I Would like to know what are all the differences between abstract classes and static classes in C#
When do I use what and why?
Is it true the abstract class is a class which we cannot create instances of it?
Thanks
I would like to know what are all the differences between abstract classes and static classes in C#.
Don't ask questions like that. I could spend hours listing hundreds of differences, none of which would be relevant to you.
What is the most important difference between abstract classes and static classes in C#?
That's more like it.
An abstract class is usually intended to model something in a type hierarchy. For example, a truck is a kind of vehicle, and an airplane is a kind of vehicle, so you might have a base class Vehicle and derived classes Truck and Airplane. But "Vehicle" is abstract; there are no vehicles which are just vehicles without being some more specific kind of thing. You represent that concept with an abstract class.
A static class by contrast is not intended to model anything at all. It's just a convenient way of storing a bunch of code. Really it shouldn't be a class at all; VB made a better choice by calling such things "modules" rather than "classes". Though technically they inherit from object, static classes are logically not really in a type hierarchy at all. They're just a bucket for holding static members.
Static classes are often used as containers of extension methods.
When do I use what and why?
Use an abstract class when you want to build a model of the form "an X is a kind of Y". Like "a Car is a kind of Vehicle" or "a Square is a kind of Shape" or "a Magazine is a kind of Publication", where the "Y" is an abstract concept. Don't use it for things like "an Employee is a kind of Person" -- Person should be concrete. Person is not an abstract concept; there are people who are just people, but there are no vehicles that are not something else.
Use a static class when you want to make extension methods, or when you have a bunch of code that fits logically together but does not associate with any object. For example, if you have a bunch of related math routines, that's a good candidate for a static class.
Is it true the abstract class is a class which we cannot create instances of it?
No. That is not true. You can create instances of an abstract class. You do so by creating an instance of a more derived class.
Vehicle v = new Car();
Clearly v refers to an instance of Vehicle, and therefore you can create an instance of an abstract class. What you cannot do is create an instance of an abstract class that is not also an instance of a more derived concrete class.
By contrast, you cannot create an instance of a static class at all.
Here's a question you didn't ask:
What is the implementation relationship between static classes and abstract classes?
Static classes actually do not really exist as a concept in the CLR. When you say "static" on a class, what we actually do is generate an abstract sealed class with no public constructors. Since it is abstract, you cannot create one directly. Since it is sealed, you cannot create a more derived class and instantiate that.
It's true that it's not possible to create an instance of an abstract or static class but that's about where the similarities end.
Can inherit from abstract cannot inherit from static
Can have instance methods on abstract cannot have instance on static
An abstract class can implement an interface a static class cannot
Fundamentally they are trying to serve two different purposes
An abstract class forms a blue print / pattern which is then implemented in derived classes in different and (hopefully) transparent ways
A static class is simply a container for a collection of possibly related static methods
An abstract class is a class that must be inherited to be used — it can only be inherited.
You can create instances of classes that inherit it.
A static class is a class that cannot have instances at all; such a class only has static members.
static classes cannot be inherited, nor can they inherit other classes.
True, an abstract class cannot be instantiated, but instead forms the base of other classes. The benefit is that you can put functionality into the abstract class to aid reuse.
A static class is one that is instantiated by the CLR when required. There can only be one instance of it any time. Using static classes is very useful, but care must be taken around threading and simultaneous access.

What's the difference between an abstract class and a static one?

Neither is instantiable. What are the differences, and in what situations might you use one or the other?
static indicates the class can only have static members and you cannot create an instance of it. This is used for stateless functionality (for example a type that just defines extension methods, or utility methods). You can also declare a member static on a non-static class. This allows you to attach functionality to a type without having to instantiate it.
Here's more detail on using static members and classes.
abstracts define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. Think of them as, I suppose, a blue print and a contract. This is a core concept for OOP.
Here's more detail on using abstracts.
Here is a short summary:
A static class can only contain static members (it is just a container for methods that do not logically belong to an instance of any standard class)
An abstract class can contain all usual kinds of members (static, abstract and also instance)
The key difference is that you can inherit from an abstract class, but you cannot inherit from a static class. Technically speaking, the .NET runtime doesn't have any notion of static classes, so the C# compiler compiles them as classes that are both abstract and sealed (meaning that you cannot inherit from them).
So, static classes are abstract classes that are also sealed (although this is not the usual way to look at the problem if you are C# programmer) and contain only static members (which is enforced by the C# compiler).
An abstract class is intended to be used as a base of a class inheritance hierarchy. A static class cannot be the base of a class inheritance hierarchy.
A static class is intended for singleton state or stateless functionality. An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses. Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.
The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated. Beyond that, they are completely different animals with completely different use cases.
The CLR has no notion of static classes, it is specific to C#. The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed. That prevents any language from instantiating such a class. This is what it looks like when you run Ildasm:
.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
extends [mscorlib]System.Object
{
}
Making it sealed is very much the point of a static class, it is used as a container for static methods and fields. Which makes them act like global variables and functions like you have in languages like C or Pascal.
An abstract class is very much the opposite, it is designed to be derived from. A abstract class that has all of its member abstract acts like an interface. C# has a keyword for that, making static class and interface the exact opposites.
Abstract classes get instantiated indirectly via derived classes. They provide common behaviour and instance state, but signal that more is required and must be provided by derived concrete classes. For example, Transform might be an abstract class: it declares a common Apply(Shape) method, but no implementation of that method. Concrete derived classes like Rotation or Translation will implement that method, and those classes can be instantiated.
Static classes cannot be instantiated, and any state is at the class level rather than the instance level. They are typically used to define utility methods where there is no state associated with the methods. Transform couldn't be a static class, because the concrete derived classes need per-instance state (e.g. Rotation needs a per-instance Angle, because different Rotation transforms could be by different angles).
Abstract classes are intended to be used as base classes; they cannot have direct instances. Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.
Example: consider you have a complex application, where users may log-in to. Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it. One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:
abstract class Authenticator {
protected Dictionary<string,User> userCache;
...
public User LoadUser(string name) {
User user;
if( userCache.TryGet(name, out user) ) return user;
else {
user = LoadFromStore(name);
userCache.Add(name, user);
return user;
}
}
protected abstract User LoadFromStore(string name);
}
Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.
Static class are a different matter alltogether. They are essentially a place to keep your utility functions:
static class StrUtil {
public static string TrimWhitespace(string str) {
...
}
}
Think of them as some kind of special namespace, which can only contain static members. Basically, a place to put functions.
Abstract Class (Base class):
Enables other classes to inherit from this class (one class acquires the properties (methods and fields) of another) , but forbids to instantiate i.e we cannot have objects of this class.
http://csharp.net-tutorials.com/classes/abstract-classes
Static Class:
This class cannot be instantiated. Also this class cannot be inherited. To access methods of this class, you can directly use classname.method.
https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx
Abstract class main purpose is to define one or more abstract method(s).
Any class extending Abstract class will implement the abstract method or else its also need to be declared as "Abstract".
But, its also possible to declare a class as "Abstract" without implementing any abstract method(s) in it. See the sample below.
public abstract class AbstractTest {
public void abcd(){}
public static void main(String[] args) {
System.out.print("hi...");
}
}
Only inner class can be declared as "Static", see the code below.
Upper/encapsulating class can't be declared as "Static".
It can be accessed by using Upper/encapsulating class variable.Static-inner-classname i.e same as any static method invocation using class name.
public class StaticTest {
public static void main(String ag[]){
System.out.println("hello...1");
StaticTest.StaticTest2.meth2();
}
public static class StaticTest2 {
public static void meth2(){
System.out.print("hello...2");
}
}
}
Main difference between the two is extensibility.
CLR marks all 'static' classes as 'abstract & sealed' behind the scene (i.e., they cannot be inherited hence cannot be extended) and .NET Framework CLR loads them automatically when containing program or namespace is loaded. This gives performance gain on runtime.
Philosophy behind 'abstract' classes is capitalizing all common features of all extended classes in one place.
Hope it helps.

C# inheritence and static classes

Why can't a static class be inherited into a normal class?
If B inherits from (is a subclass of) A, that means an instance of B can be stored in a variable of type A, and its virtual methods will call those of class B.
For static classes, you don't have the concept of an instance of the class, so there's no way to inherit. You might have better luck with a static (singleton) reference to a regular class.
From Static Classes and Static Class Members (C# Programming Guide)
Creating a static class is therefore
basically the same as creating a class
that contains only static members and
a private constructor. A private
constructor prevents the class from
being instantiated. The advantage of
using a static class is that the
compiler can check to make sure that
no instance members are accidentally
added. The compiler will guarantee
that instances of this class cannot be
created.
Static classes are sealed and
therefore cannot be inherited. They
cannot inherit from any class except
Object. Static classes cannot contain
an instance constructor; however, they
can contain a static constructor.
As an alternative to inheriting from a static class, you can assign extension methods to interfaces.
You can not inherit a static class - The reason is simple. Static classes are marked as abstract and sealed in compiled IL which can be neither instantiated nor inherited.
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Source:
Why can't I inherit static classes?

Categories