It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
While studying C# in ASP.net I have trouble understanding several classes. In which scenario should I use the following classes private,public,protected,abstract,static,sealed ?
It would be better if someone can explain these with easy examples.
Those are not classes.
private, protected and public are access modifiers. They indicate which other code can see the code they affect:
public class Foo
{
private int _myOwn = 1;
protected int _mineAndChildren = 2;
public int _everyOnes = 3;
}
public class Bar : Foo
{
public void Method()
{
_myOwn = 2; // Illegal - can't access private member
_mineAndChildren = 3; // Works
_everyOnes = 4; // Works
}
}
public class Unrelated
{
public void Method()
{
Foo instance = new Foo();
instance._myOwn = 2; // Illegal - can't access private member
instance._mineAndChildren = 3; // Illegal
instance._everyOnes = 4; // Works
}
}
An abstract class is one that may contain abstract members. An abstract member has no implementation, so all derived classes must implement the abstract members.
A sealed class cannot be inherited. A static class is sealed, but also can only contain static members.
I suggest you start with "Getting Started with Visual C#. This is a very basic question.
public, private and protected aren't classes, they're access modifiers. They change what is allowed to access the classes that you decorate with them. They apply to classes as well as the members of classes.
public items can be seen from anywhere
private classes can only be seen from within the same file
private members of classes can only be seen within that class
protected members are visible from within the class and its descendants
internal classes are public within the same assembly.
The abstract keyword marks a class or method as having no implementation, and it must be overridden (with the override keyword) in a derived type before you can use it.
A sealed class cannot be inherited from.
Using the static keyword on a class member indicates that the member belongs to the class itself, rather than a specific instance of it. Marking a class as static imposes the restriction that all members of this class must also be static.
private, public and protected indicate who can access members of a class. private means no one outside the class can see it. public means everyone can see it. protected is just like private, but subclasses can access it.
class Data
{
private int counter; // only accessible to class functions
protected int id; // accessible to class and subclass functions
public string name; // accessible from all code
}
abstract means this is not a finished class - it is meant to be used as a base for subclasses. Often there are virtual functions in its definition, functions intended to be "filled in" by a subclass.
abstract class Window
{
// cannot create objects of this class directly
// need to create sub class
}
static on the class definition means there's only one global copy. It pretty much reverts the class to an old-style module. static against a member indicates that it is a global member within the class, there is not a different version for every object you make of that class.
static class Configuration
{
// only one instance of the object
}
class Data
{
private static int counter; // all Data objects access this one counter
private int id; // each Data object has a different id
}
sealed prevents subclasses being created; it can also be applied to individual functions to prevent them being overridden in a subclass.
sealed class TelephoneNumber
{
// cannot create subclass of TelephoneNumber
}
class Address
{
public sealed string FormatAddress()
{
// this function cannot be overridden on a subclass
}
}
I down't can comment your question but i have an little adition but importan information for you.
access modifiers are only an compiler-feature. every .net-programm can ignore this by using reflection and can access your private flaged classes and methodes.
An exampel:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectPrivateMembers
{
class Program
{
static void Main(string[] args)
{
ConstructorInfo ci = typeof(Hello).GetConstructor(BindingFlags.NonPublic| BindingFlags.Instance ,null,System.Type.EmptyTypes,null);
object helloObject = ci.Invoke(System.Type.EmptyTypes);
MethodInfo[] helloObjectMethods = helloObject.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly| BindingFlags.Instance );
foreach (MethodInfo mi in helloObjectMethods)
{
mi.Invoke(helloObject, System.Type.EmptyTypes);
}
Console.ReadLine();
}
}
public class Hello
{
private Hello()
{
Console.WriteLine("Private Constructor");
}
public void HelloPub()
{
Console.WriteLine("Public Hello");
}
private void HelloPriv()
{
Console.WriteLine("Private Hello");
}
}
}
Source: Reflection with Private Members
The first three are access modifiers, they can be applied to types and members.
private means something can only be accessed from within its declaring type.
protected means something can be accessed by inheritors of the declaring type, or by something in the type itself.
public means something can be accessed from anywhere that has a valid reference to the declaring type.
The rest can also be applied to both types and members.
abstract (on a member) means the member has no implementation (the implementation must be provided by inheritors of the type) or (on a type) that the type cannot be instantiated (only inherited).
static (on a member) means that the member is shared statically by all callers, or (on a type) that the type can only contain static members and therefore cannot be instantiated (i.e. it doesn't have any instance members and therefore cannot serve any instances of itself).
sealed (on an inherited virtual or abstract member) means that inheritors of the type cannot override the member, or (on a type) that the type cannot be inherited from.
There are a couple of other modifiers you should be aware of:
internal is another access modifier that means that something can be accessed by anything within the same assembly (or project) as the declaring type.
Also,
virtual (on a member) means that the member may optionally be overridden by an inheritor of the type, but supplies its own default implementation.
partial (on a member) allows you to provide the signature of a member in one file, and the implementation in another, or (on a type) allows you to split the definition of a type across multiple code files.
What you have there are modifiers, not types of classes.
private, public, and protected are Access Modifiers. They define how accessible you want the code to be.
Before looking into the other modifiers you have listed, I would suggest attempting to get a grasp on Object Oriented Programming. Here is a link full of good resources you can review.
private,public,protected are the access modfier supported by c# language : here is the msdn link for more detail Access Modifiers
Abstract and Sealed Classes and Class Members
Static Classes and Static Class Members
private and public refer to the visibility of the class outside the assembly (e.g. DLL or EXE) it lives in. protected is a modifier for methods, it means only classes that inherit from the declarator can call the method.
abstract identifies a class that cannot be created directly, and is designed only to provide a base for other classes.
Applied to methods, static means they can be accessed as part of the type, rather than an instance of the class:
class Bar {
static void Foo() { ... }
void Foo() { ... }
}
The first one can be called like this:
Bar.Foo();
The second one only like this:
Bar b = new Bar();
b.Foo();
Applied to classes, static limits the class to contain only static methods. It's more aesthetic than anything else, but it also helps the compiler.
The sealed modifier tells the compiler that a class cannot be inherited from.
Related
When posting this question my hope was to find a way how to reference/point to
an abstract class that that could be used by a worker/holder.
As the comments by #progman suggested and #laryx-decidua there is no way to hold a reference to an abstract class, but one can only hold a reference to a instantiated object.
Below you can find what I think is their proposed solution. To me this is an ugly solution, and I would have liked to have one that derives multiple static classes from an abstract base class and the holder gets references to those static classes to do its work. Deriving a static class form an abstract class Why you can't drive a static class is it seems prohibited by design and indicates bad architecture; although I don't see why the solution above is any better.
Suggested Solution
using System;
using System.Collections.Generic;
public abstract class BaseClass
{
// Some declarative knowledge
public int value;
protected BaseClass(int value){
this.value = value;
}
// Some procedural
public abstract void execute();
}
public class ConcreteClass1 : BaseClass
{
public ConcreteClass1() : base(42) {}
public override void execute()
{
Console.WriteLine("In Concrete1! Value " + value);
}
}
public class ConcreteClass2 : BaseClass
{
public ConcreteClass2() : base(8888) { }
public override void execute()
{
Console.WriteLine("In Concrete2! Value " + value);
}
}
public class Holder
{
BaseClass activeClass;
public void setClass(BaseClass newClass){
activeClass = newClass;
}
public void doWork()
{
int x;
activeClass.execute();
x = activeClass.value * activeClass.value;
Console.WriteLine("Holder has done its work: " + x);
}
}
class MainClass
{
static void Main(string[] args)
{
List<BaseClass> classes = new List<BaseClass>();
classes.Add(new ConcreteClass1());
classes.Add(new ConcreteClass2());
Holder holder = new Holder();
holder.setClass(classes[0]);
holder.doWork();
holder.setClass(classes[1]);
holder.doWork();
holder.setClass(classes[0]);
holder.doWork();
}
}
producing
In Concrete1! Value 42
Holder has done its work: 1764
In Concrete2! Value 8888
Holder has done its work: 78996544
In Concrete1! Value 42
Holder has done its work: 1764
Disclaimer: I don't speak C#, but I suspect the situation is similar to C++. The rest of the answer is based on my C++ and general OOP experience.
If I understood you correctly, you'd like to hold derived class object(s) through a base class reference and invoke a polymorphic ("virtual") method on those objects. Because you expect those derived classes to be "stateless" (i.e. no data members), you thought maybe you could "get away with" static (and/or abstract) classes.
The problem is that you need to instantiate something to put into your Holder objects, because a reference (or a pointer) can refer to (point to) only to a concrete object. So you need to instantiate objects that will be referred to via a reference in Holder, as some of the commenters have already pointed out. That's why abstract classes won't do -- they cannot be instantiated.
If there were an OOP language that supports references to types , plus some mechanism that can do the following: "Hmm, here is a reference AnimalTypeRef to the (possibly abstract) base class type Animal. AnimalTypeRef actually refers to the derived class type Elephant. Now, the user wants to invoke a virtual method Animal::make_noise() that does not use any class state, so let's invoke the corresponding method Elephant::make_noise() that overrides it and returns this :-)." -- well, then you could do what you have asked for.
I suspect this has not been implemented in C++ or C# because there are not too many use cases for it, and actually the same thing can be done with the general mechanism that requires that references refer to concrete objects.
Just go ahead and derive concrete (non-abstract) classes from your abstract base class, and don't worry about their statelessness. It's perfectly OK to define and use concrete objects that have no data members. Instantiate them, then initialise a Holder object with them, using a reference to the (abstract) base class and that's it. Polymorphic method invocation through base class references will do the rest.
Apparently this works in Java:
class BigClass
{
public SecretClass not_so_secret = new SecretClass();
public class SecretClass
{
// Methods and stuff
}
}
But is there no equivalent in c#? Where I can create an instance of BigClass but NOT be allowed to create the subclass SecretClass:
class testing_class
{
BigClass BIG_CLASS_SHOULD_BE_ALLOWED = new BigClass();
BigClass.SecretClass SUB_CLASS_SHOULD_NOT = new BigClass.SecretClass();
}
I've tried combinations of internal (which sounded right...), private, protected - basically just all of them now :D
Is it a fundamental no-way-round principle in c# to always have this one-way street for access modifiers?
By the way I did find a sort-of answer here referring to Kotlin (whatever that is) and it seems to be a strict thing that just wouldn't make sense to some or be dangerous for some reason - public instances of an "internally" created private class
Is there no way to achieve that level of access in c#?
If you want to make a member (field, property, method, event, delegate or nested type) public, all the types exposed by this member must be public.
However, there is a trick on how you can make the class only instantiateable within BigClass: Make the class abstract, and if you need to write a constructor, make it protected or, since C# 7.2 private protected (see below). Then derive a nested private class from it.
public class BigClass
{
public SecretClass not_so_secret = new VerySecretClass();
public abstract class SecretClass
{
}
private class VerySecretClass : SecretClass
{
}
}
Also make everything private or protected that you don't need to expose. You can even give the setters more restrictive access modifiers.
public string Text { get; private set; } // or: protected set;
It also helps to make things internal if you are writing a class library. It makes things invisible for other assemblies.
Since C# 7.2 there is also a new level of accessibility (from C# 7 Series, Part 5: Private Protected):
Private Protected
Private Protected: The member declared with this accessibility can be visible within the types derived from this containing type within
the containing assembly. It is not visible to any types not derived
from the containing type, or outside of the containing assembly. i.e.,
the access is limited to derived types within the containing assembly.
Are private members inherited when inheriting the class in c#?
I have read some topic related to this, somebody telling that private members are inherited but cannot access the private members, somebody telling that it is not inherited when inheriting the class. Please explain the concept. if it is inheriting can any body give an explanation?
thanks
If I understand your question correctly then you're not concerned about the accessibility you are only concerned about private members are inherited or not
Answer is yes, all private members are inherited but you cant access them without reflection.
public class Base
{
private int value = 5;
public int GetValue()
{
return value;
}
}
public class Inherited : Base
{
public void PrintValue()
{
Console.WriteLine(GetValue());
}
}
static void Main()
{
new Inherited().PrintValue();//prints 5
}
You can mark things as protected, in which case you can access them from derived types.
Edit: In terms of whether they inherit, then yes they do. The child class is still of the parent classes type, and thus inherits everything. The child just cannot access it directly, but if you call base class methods that use the private parent field, that would work fine.
Private members can't be inherited, only protected which are like extended private members.
Like Sriram says, yes, private members do get inherited, but they ar enot accessible.
If they would not get inherited, protected or public properties references private members would break in inherited classes.
class myBase
{
private string _myProp;
protected string MyProp
{
get
{
return _myProp;
}
set
{
_myProp = value;
}
}
}
class myChild : myBase
{
public myChild()
{
_myProp = "SomeString"; // This will fail!!!
this.Myprop = "SomeString"; // This works
}
}
Here in the child class, you cannot access _myProp directly as it is private in the base class. However, the memeber is inherited, so it is accessible through the protected property MyProp.
Members marked as private can be accessed only on the type where they are defined. You cannot access them from derived types.
Members marked as protected can be accessed on the type where they are defined and on derived types.
Members marked as internal can be accessed only from the assembly where the type is defined.
You may combine the protected and the internal access modifier.
When talking about values of private members: Of course they are inherited. A derived class always also is of the type of the base class. If the base class holds a private value to store some data, the derived class will do that, too - only that you can't access that value from the derived class.
Please also read the relevant article on Accessibility Levels in the MSDN.
What you said about private fields being inherited is totally right.
Here what happens: A subclass will inherit the behaviour of your base class. That behaviour might need some fields to work. So, your subclass will reserve some space for them, but you will not be able to manipulate those fields, only by using methods (public and protected ones)
In other words, your sub class inherits base class fields by holding them in memory, but it cannot access them.
On low level, it is your compiler that prevents you from accessing/changing those private fields, but even using reflection you can still do so.
If you need any clarification, let me know
From http://msdn.microsoft.com/en-us/library/ms173149.aspx
A derived class has access to the public, protected, internal,
and protected internal members of a base class. Even though a
derived class inherits the private members of a base class, it
cannot access those members. However, all those private members are
still present in the derived class and can do the same work they would
do in the base class itself. For example, suppose that a protected
base class method accesses a private field. That field has to be
present in the derived class in order for the inherited base class
method to work properly.
To expand on what's been said, privates can be accessed by a subclass when inner scope is in play. For example, the following will compile:
class A
{
private int _private;
class B : A
{
void Foo()
{
this._private = 2;
}
}
}
Short answer: yes, but you are unable to access them directly.
When class A is derived from class B, and B has a private property then that property will be there for an instance derived of class A. You are, however unable to access it. It must be there because the behavour specified in class B depends on it.
funfact:
It is actually possible to still access the private property with a thing called reflection. But don't worry about that and you should not use reflection for this purpose unless you really need to know what is going on and what you're doing.
The simplest answer you can not access the private variables of base class in derived class directly but yes this private objects and values are initialized in base class when overriding class object is initiated (thus base class variables are inherited) and you can access them using some property or function if base class exposes them.
To make explanation more clear,
class A
{
private int i;
private int j;
protected int k;
public A()
{
i = j = k = 5;
}
}
class B : A
{
private int i; //The same variable exist in base class but since it is private I can declare it
private int j;
private int k; //Here I get warning, B.k hides inherited member A.k'. Use the new keyword if hiding was intended. F:\Deepak\deepak\Learning\ClientUdpSocketCommunication\ClientUdpSocketCommunication\Program.cs 210 25 ClientUdpSocketCommunication
private int l;
private int m;
private int n;
public B()
{
i= j = this.k = l = m = n = 7; // Here I have used this.k to tell compiler that I want to initialize value of k variable of B.k class
base.k = 5; //I am assigning and accessing base class variable as it is protected
}
}
If an object of class B is initialized then, A.i, A.j, A.k variable will be initialized, with B.i, B.j, B.k, B.l variables and if base class exposes function or properties then I can access all the base class variables.
This question already has answers here:
What's the difference between a public constructor in an internal class and an internal constructor?
(5 answers)
Closed 9 years ago.
I've seen some C# code that declares a class with an internal modifier, with a public constructor:
internal class SomeClass
{
public SomeClass()
{
}
}
What is the point of having a public constructor, if the visibility of the entire class is internal, thus it can be seen only inside the defining assembly?
Also, does this make any sense in case SomeClass is a nested class?
The internal class scope overrides the public MyClass() constructor scope, making the constructor internal.
Using public on the constructor makes it easier to update the class to public later, but confuses intent. I don't do it.
Edit 3: I missed part of your question. It is still fine to do that if your class is nested. The nesting can't make any difference, even if it is nested in a private class in a public class in a ... (see C# language specification - 3.5.2 Accessibility domains).
EDIT: And, if i recall, if the ctor is internal, it can't be used as a generic type where there is a constraint requiring where T : new(), this would require a public constructor (ref. C# language specification (version 4.0) - 4.4.3 Bound and unbound types).
Edit 2: Code sample demonstrating the above
class Program
{
internal class InternalClass {
internal InternalClass() { }
}
internal class InternalClassPublicCtor {
public InternalClassPublicCtor() { }
}
internal class GenericClass<T>
where T : new() {}
static void Main(string[] args) {
GenericClass<InternalClass> doesNotCompile = new GenericClass<InternalClass>();
GenericClass<InternalClassPublicCtor> doesCompile = new GenericClass<InternalClassPublicCtor>();
}
}
From MSDN - Access Modifiers (C# Programming Guide):
Normally, the accessibility of a member is not greater than the accessibility of the type that contains it. However, a public member of an internal class might be accessible from outside the assembly if the member implements interface methods or overrides virtual methods that are defined in a public base class.
So if, for example, you have an internal implementation of a public interface, you can still expose certain members as public.
Additionally, suppose you suddenly want your internal class to be public. It's a lot easier simply to change the access modifier on the class than all of the members.
In C#, a superclass's static members are "inherited" into the subclasses scope. For instance:
class A { public static int M() { return 1; } }
class B : A {}
class C : A { public new static int M() { return 2; } }
[...]
A.M(); //returns 1
B.M(); //returns 1 - this is equivalent to A.M()
C.M(); //returns 2 - this is not equivalent to A.M()
Now, you can't inherit static classes, and the only place I can imagine that static inheritance might matter ignores it entirely: although you can make a generic constraint that requires a type parameter T to be a subclass of A, you still cannot call T.M() (which probably simplifies things for the VM), let alone write a different M implementation in a subclass and use that.
So, the "inheritance" of static members merely looks like namespace pollution; even if you explicitly qualify the name (i.e. B.M) A's version is still resolved.
Edit compare with namespaces:
namespace N1{ class X(); }
namespace N1.N2 { class X(); }
namespace N1.N2.N3 { [...] }
Within N1.N2.N3 It makes sense that if I use X without qualification it refers to N1.N2.X. But if I explicitly refer to N1.N2.N3.X - and no such class exists - I don't expect it to find N2's version; and indeed to compiler reports an error if you try this. By contrast, if I explicitly refer to B.M(), why doesn't the compiler report an error? After all, there's no "M" method in "B"...
What purpose does this inheritance have? Can this feature be used constructively somehow?
So, the "inheritance" of static
members merely looks like namespace
pollution
That's right, except that one guy's pollution is another guy's added spicy flavouring.
I think Martin Fowler, in his work on DSLs, has suggested using inheritance in this way to allow convenient access to static methods, allowing those methods to be used without class name qualification. So the calling code has to be in a class that inherits the class in which the methods are defined. (I think it's a rotten idea.)
In my opinion, static members should not be mixed into a class with a non-static purpose, and the issue you raise here is part of the reason why it's important not to mix them.
Hiding private static mutable data inside the implementation of an otherwise "instancey" class is particularly horrible. But then there are static methods, which are even worse mixers. Here's a typical use of static methods mixed into a class:
public class Thing
{
// typical per-instance stuff
int _member1;
protected virtual void Foo() { ... }
public void Bar() { ... }
// factory method
public static Thing Make()
{
return new Thing();
}
}
It's the static factory method pattern. It's pointless most of the time, but even worse is that now we have this:
public class AnotherThing : Thing { }
This now has a static Make method which returns a Thing, not a AnotherThing.
This kind of mismatch strongly implies that anything with static methods should be sealed. Static members fail to integrate well with inheritance. It makes no sense to have them heritable. So I keep static things in separate static classes, and I gripe about redundantly having to declare every member static when I've already said that the class is static.
But it's just one of those too-late-now things. All real, working languages (and libraries, and products) have a few of them. C# has remarkably few.
I rather have access to all my based static members in derived classes.
Otherwise i would need to know exactly where the static member was defined and call it explicitly.
When using Intellisense you can automatically know every static member available to that kind of class.
Of course, they are not inherited, it's just a shortcut
That's how it works, would probably just be a stupid answer in most cases. But in this case, it is how it works; since you derive from A you say that you are A + the extra features you add.
Therefore you need to be able to access the same variables that you would through an instance of A.
However, inheriting a static class makes no sense while access to the static members / fields / methods does.
An example of this is the following:
internal class BaseUser
{
public static string DefaultUserPool { get; set; }
}
internal class User : BaseUser
{
public int Id { get; set; }
public string Name { get; set; }
public User Parent { get; set; }
}
Where the test looks like this:
User.DefaultUserPool = "Test";
BaseUser.DefaultUserPool = "Second Test";
Console.WriteLine(User.DefaultUserPool);
Console.WriteLine(BaseUser.DefaultUserPool);
Both of the WriteLines outputs "Second Test", this is because both BaseUser and User should use DefaultUserPool, by design. And overriding static implemented methods wouldn't make mucn sense since it's just an accessor in the child-class.
There can be only one. Overriding it would mean that there's a new implementation for that sub-class, which would kill the term "static".
Actually, as I understand it, this is just a shortcut provided by the compiler. Syntax sugar. B.M() will just compile to A.M() since B does not have a static M() and A does. It's for easier writing, nothing else. There is no "static inheritance".
Added: And the requirement for new when "redefining" is just so that you don't accidentally shoot yourself in the foot.
I think it's for accessing protected static members of the base class.
class Base
{
protected static void Helper(string s)
{
Console.WriteLine(s);
}
}
class Subclass : Base
{
public void Run()
{
Helper("From the subclass");
}
}
So... What's the alternative?
The question mentions...
why doesn't the compiler report an error? After all, there's no "M" method in "B"...
But there is a derived "M" method in "B" class.
If the compiler did not present the programmer a unified virtual table for base cases, then the programmer would have to go hunting through base types to find static methods. This would break polymorphism.
Wikipedia...
Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability of one type, A, to appear as and be used like another type, B....
In strongly typed languages, polymorphism usually means that type A somehow derives from type B, or type C implements an interface that represents type B.
I always see it a means of preventing any form of polymorphism by the inheriting class on those items that you wish to retain the same function for all child classes.
ignore the above for some reason I was thinking of sealed instead of static
I suppose that you'd use static member variables and functions in order to ensure that any data or functionallity is not dependent on the a class instance as it would be instantiated only the once.
An example of use would be say a counter value that would keep a live count of all instances of a superclass's subclasses (each subclass increments the static count value on construction). This count value would be available and equal for all instances of the subclass.