What does a public constructor on an internal class mean [duplicate] - c#

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.

Related

Public instance of private class - never allowable in c#

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.

Why inheritance from a class with private constructor is disallowed [duplicate]

This question already has answers here:
If derived class inherits the private members of a base class, then why not constructors?
(4 answers)
Closed 5 years ago.
I can't find the reason that why inheriting from a base class the a private parameterless constructor is not allowed in C#. Here's the simplest example:
public class Base
{
private Base()
{
}
public string Name { get; set; }
}
public class Derived : Base
{
public Derived(string name)
{
base.Name = name;
}
}
Compiler doesn't compile this code. Why is it so? The class is not sealed of course, and while the base class is meant not to be instantiated many times (as in Singleton), I think the derived class has every right to be instantiated with a parametered constructor many times.
Why inheritance is disallowed in this case?
Because you need a constructor to instantiate a class, and the constructor is held private by the class you want to derive. No one but the class itself is allowed access to it. For all it knows it doesn't exist! (You might want to use a private constructor for the Singleton pattern for example)
If you want to allow inheritance, but keep the constructor from called outside, you need the protected keyword.
You can't access something from another class if the private modifier is used; even from a derived class.
Have a look at this: Access Modifiers
private
The type or member can be accessed only by code in the same class or
struct.
And because the Base constructor has to be called when an instance of Derived will be created you can't use private in your case. You should use protected instead.

Why can an abstract class not be sealed or static?

Why can an abstract class not be sealed or static?
And I am also confused about the question Why declare static classes as sealed and abstract in C#?.
static class cannot be marked sealed because it is made sealed by compiler by default.
Static classes are sealed and therefore cannot be inherited.
static class cannot be marked as abstract, because it would be pointless. abstract class makes sense when you want all derived classes to implement same part of the logic. But because static class cannot be derived there is no way other class will implement these gaps.
They cannot inherit from any class except Object.
Both quotes from Static Classes and Static Class Members (C# Programming Guide).
C# specification is a little more detailed about that:
10.1.1.3 Static classes
A static class may not include a sealed or abstract modifier. Note, however, that since a static class cannot be instantiated or derived from, it behaves as if it was both sealed and abstract.
You can read what does it mean for class to be sealed or abstract:
An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class.
Update
And a word about an article linked in the query you mentioned (Static Class Design). It's already stated in accepted answer from that question. If you read carefully you can see that:
√ DO declare static classes as sealed, abstract, and add a private instance constructor if your programming language does not have built-in support for static classes.
.NET (so C# as well) do have built-in support for static classes, so you don't have (and even can't) to make your classes pseudo-static by marking it both sealed and abstract.
First of all, let's start with a definition; sealed is a modifier which if applied to a class make it non-inheritable and if applied to virtual methods or properties makes them nonoverridable.
public sealed class A { ... }
public class B
{
...
public sealed string Property { get; set; }
public sealed void Method() { ... }
}
An example of its usage is to define a specialized class/method or property in which potential alterations can make them stop working as expected (for example, the Pens class of the System.Drawing namespace).
...
namespace System.Drawing
{
//
// Summary:
// Pens for all the standard colors. This class cannot be inherited.
public sealed class Pens
{
public static Pen Transparent { get; }
public static Pen Orchid { get; }
public static Pen OrangeRed { get; }
...
}
}
Because a sealed class cannot be inherited, it cannot be used as base class and by consequence, an abstract class cannot use the sealed modifier.
It's also important to mention that structs are implicitly sealed.

Usage of "Class" in C# [closed]

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.

Public and Internal members in an Internal class?

Ok, so this may be a bit of a silly question, and there's certainly the obvious answer, but I was curious if I've missed any subtleties here.
Is there any difference in terms of visibility/usability between a public member declared in an internal class and an internal member declared in an internal class?
i.e. between
internal class Foo
{
public void Bar()
{
}
}
and
internal class Foo
{
internal void Bar()
{
}
}
If you declared the method as public and also virtual, and then overrode it in a derived class that is public, the reason for using this modifier is clear. However, is this the only situation... am I missing something else?
Consider this case:
public interface IBar { void Bar(); }
internal class C : IBar
{
public void Bar() { }
}
Here C.Bar cannot be marked as internal; doing so is an error because C.Bar can be accessed by a caller of D.GetBar():
public class D
{
public static IBar GetBar() { return new C(); }
}
A commenter asked a follow-up question: is an explicit implementation of an interface method considered to be public, or private? (C# does not allow you to put an access modifier on an explicit implementation.)
Take a step back and think about what exactly is "public" or "private" about a member: people think wrong things like "private means that a method cannot be called from outside the class", but that's not true; the class could make a delegate to a private method, pass it to anyone, and they can then call a private method.
Rather, accessibility determines where the name of a thing can be used! Explicit interface implementations do not add a name to the class declaration space in the first place; they can only be referred to by name via the interface, not the class. It really doesn't make sense to think of explicit interface implementations as public or private because they don't have a name you can refer to.
A public member is still just internal when in an internal class.
From MSDN:
The accessibility of a member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal type has only internal accessibility
Think of it this way, I would access a public property on....? A class I can't see? :)
Eric's answer is very important in this case, if it's exposed via an interface and not directly it does make a difference, just depends if you're in that situation with the member you're dealing with.
public members of an internal class can override public members of public base classes and, therefore, be a little more exposed... if indirectly.
Just faced with another example where there is difference between those two, when used from XAML in WPF.
XAML:
<Button Tag="{x:Static vm:Foo+Bar.e1}" />
Code with internal enum compiles successfully:
internal class Foo
{
internal enum Bar
{
e1,
e2,
}
}
But surprisingly changing it to public results in error:
internal class Foo
{
public enum Bar
{
e1,
e2,
}
}
The last example produces compilation error:
error MC3064: Only public or internal classes can be used within markup. 'Bar' type is not public or internal.
Unfortunately, I can't explain what's wrong with public in this case. My guess is "just because WPF works that way". Just change modifier of the nested class to internal to get rid of error.
If it comes to reflection it matters if the member is public or not:
For example you even could pass a nested private class to a WPF binding and the binding would work against the public properties just as usual.

Categories