Private class with Public method? - c#

Here is a piece of code:
private class myClass
{
public static void Main()
{
}
}
'or'
private class myClass
{
public void method()
{
}
}
I know, first one will not work. And second one will.
But why first is not working? Is there any specific reason for it?
Actually looking for a solution in this perspective, thats why made it bold. Sorry

It would be meaningful in this scenario; you have a public class SomeClass, inside which you want to encapsulate some functionality that is only relevant to SomeClass. You could do this by declaring a private class (SomePrivateClass in my example) within SomeClass, as shown below.
public class SomeClass
{
private class SomePrivateClass
{
public void DoSomething()
{
}
}
// Only SomeClass has access to SomePrivateClass,
// and can access its public methods, properties etc
}
This holds true regardless of whether SomePrivateClass is static, or contains public static methods.
I would call this a nested class, and it is explored in another StackOverflow thread.

Richard Ev gave a use case of access inside a nested classes. Another use case for nested classes is private implementation of a public interface:
public class MySpecialCollection<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return new MySpecialEnumerator(...);
}
private class MySpecialEnumerator : IEnumerator<T>
{
public bool MoveNext() { ... }
public T Current
{
get { return ...; }
}
// etc...
}
}
This allows one to provide a private (or protected or internal) implementation of a public interface or base class. The consumer need not know nor care about the concrete implementation. This can also be done without nested classes by having the MySpecialEnumerator class be internal, as you cannot have non-nested private classes.
The BCL uses non-public implementations extensively. For example, objects returned by LINQ operators are non-public classes that implement IEnumerable<T>.

This code is syntactically correct. But the big question is: is it useful, or at least usable in the context where you want to use it? Probably not, since the Main method must be in a public class.

Main() method is where application execution begin, so the reason you cannot compile your first class (with public static void Main()) is because you already have Main method somewhere else in your application. The compiler don't know where to begin execute your application.
Your application must have only one Main method to compile with default behavior otherwise you need to add /main option when you compile it.

Related

Class<T> and static Class, Best Practices?

I have a scenario that (simplified) is as follows:
public static class Example
{
public const int CONSTANT_VALUE = 1;
public static Example<T> Create<T>(IEnumerable<T> argument)
where T : class
{
return new Example<T>(argument);
}
//More overloads of Create<T>, possibly other static methods, etc..
}
public class Example<T>
where T : class
{
public Example(IEnumerable<T> argument)
{
//Do Stuff
//Nothing like this in the real code, just example
//that constants are used from the other class.
if (something == Example.CONSTANT_VALUE)
{
//Do A Thing
}
}
//Lots more code
}
The basic idea is that I can have static methods, constants, etc. available through the name of the class through the static class, while the actual implementation is in the type-argumented non-static class.
My question is whether or not this is a good way to set this up. Is there a way to put some static methods and constants that don't care what the type argument is on Example<T>? Is there otherwise a more recommended pattern? What I have works fine, but I wanted to know if there are other ways since this is the first time I've ended up doing something like this (not that it's conceptually new to me, just never had need).
This would only make sense if the constants are public. If they are only for internal use inside Example<T> then this is pointless, becuase you can reference them without a fully qualified name.
If the constants are of public use, I wouldn't use this pattern anayways; Example and Example<T> are two different classes, it is potentially confusing to any user, and not immeadiately obvious, that constants defined in the non generic class are aplicable to the generic one.
You are only avoding the user a few keystrokes, I'm not really sure it is worth it.
Update: other options
In this scenario, I'd use the following factory pattern (assuming the users are outside your assembly)
public class Example<T>
{
internal Example() { } //disallow users from instantiating this class
...
}
public static class Example
{
public const int Constant = ...
public static Example<T> Create<T>() { return new ... }
}
And now all users will interact only with Example and avoid using Example<T>. You could even enforce this with users of your own assembly, you'd just need to make Example<T> a private nested class implementing a public interface:
public interface IExample<T>
{
...
}
public static class Example
{
private class Example<T>: IExample<T> { ... }
public static IExample<T> Create<T>() { ... }
....
}
Unless there is a reason this wouldn't work in your case, I would prefer to use a non-static base class Example, and then let Example<T> inherit from this class. That way you get direct access to all the methods in Example, without having to qualify with the name. Of course, this assumes that the Example class is exclusively to be used in connection with the various typed classes Example<T>.

Any use of declaring a private static class in c#?

Is there any use of declaring a static class as private.Here is the code below:
static class DerivedClass
{
private static string GetVal()
{
return "Hello";
}
}
The sample code you provided actually illustrates an internal class, not a private class. This is perfectly fine and is done all the time. It means the methods of the class are available from other classes within the same module, but not externally.
If you mean declaring private members of static classes, sure there is.
static class DerivedClass
{
public static string GetVal()
{
return GetValInternal();
}
private static string GetValInternal()
{
return "Hello";
}
}
If you mean declaring a private static nested classes (because only nested classes can be private, according to the documentation), then you can do it, but there's probably no reason to do it.
class SomeClass
{
private static class DerivedClass
{
public static string GetVal()
{
return "Hello";
}
}
}
Is equivalent to
class SomeClass
{
private static string GetVal()
{
return "Hello";
}
}
By default classes with no access modifiers like in your example are internal, not private. See this reference: http://msdn.microsoft.com/en-us/library/ms173121.aspx. This means that you can access this class from anywhere inside the library/project. This makes sense because it allows you to use the class internally without necessarily exposing it to the outside world.
Explicitly declaring it as private however makes sense in some rare cases only in my opinion. I have used it before for nested classes simply to group certain things together and make my code prettier/more readable. However I find that if I am creating nested classes it usually means that I need to redesign my code and pull some of it into separate files and separate classes. Rather try to stick to one class per file.

C#: Giving access to private members without 3-fold code duplication

I have a class
public class Foo{
public Foo{...}
private void someFunction(){...}
...
private Acessor{
new Acessor
}
}
with some private functionality (someFunction). However, sometimes, I want to allow another class to call Foo.SomeFunction, so I have an inner class access Foo and pass out that:
public class Foo{
public Foo{...}
private void someFunction(){...}
...
public Acessor{
Foo _myFoo;
new Acessor(Foo foo){_myFoo = foo;}
public void someFunction(){
_myFoo.someFunction();
}
}
}
With this code, if I want a Foo to give someone else pemission to call someFunction, Foo can pass out a new Foo.Accessor(this).
Unfortunately, this code allows anyone to create a Foo.Accessor initiated with a Foo, and they can access someFunction! We don't want that. However, if we make Foo.Accessor private, then we can't pass it out of Foo.
My solution right now is to make Acessor a private class and let it implement a public interface IFooAccessor; then, I pass out the Foo.Accessor as an IFooAccessor. This works, but it means that I have to declaration every method that Foo.Accessor uses an extra time in IFooAccessor. Therefore, if I want to refactor the signature of this method (for example, by having someFunction take a parameter), I would need to introduce changes in three places. I've had to do this several times, and it is starting to really bother me. Is there a better way?
If someFunction has to be accessible for classes in the same assembly, use internal instead of private modifier.
http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.71).aspx
If it has to be accessible for classes which are not in the same assemble then, it should be public. But, if it will be used by just a few classes in other assemblies, you probably should think better how you are organizing you code.
It's difficult to answer this question, since it's not clear (to me at least) what exactly you want to achieve. (You write make it difficult for someone to inadverdantly use this code in a comment).
Maybe, if the method is to be used in a special context only, then explicitly implementing an interface might be what you want:
public interface ISomeContract {
void someFunction();
}
public class Foo : ISomeContract {
public Foo() {...}
void ISomeContract.someFunction() {...}
}
This would mean, that a client of that class would have to cast it to ISomeContract to call someFunction():
var foo = new Foo();
var x = foo as ISomeContract;
x.someFunction();
I had a similar problem. A class that was simple, elegant and easy to understand, except for one ugly method that had to be called in one layer, that was not supposed to be called further down the food chain. Especially not by the consumers of this class.
What I ended up doing was to create an extension on my base class in a separate namespace that the normal callers of my classes would not be using. As my method needed private access this was combined with explicit interface implementation shown by M4N.
namespace MyProject.Whatever
{
internal interface IHidden
{
void Manipulate();
}
internal class MyClass : IHidden
{
private string privateMember = "World!";
public void SayHello()
{
Console.WriteLine("Hello " + privateMember);
}
void IHidden.Manipulate()
{
privateMember = "Universe!";
}
}
}
namespace MyProject.Whatever.Manipulatable
{
static class MyClassExtension
{
public static void Manipulate(this MyClass instance)
{
((IHidden)instance).Manipulate();
}
}
}

Visibility of nested class constructor

Is there a way to limit the instantiation of the nested class in C#? I want to prevent nested class being instantiated from any other class except the nesting class, but to allow full access to the nested class from other code.
Usually I create an interface for the functionality you want to expose to other classes, then make the nested class private and implement that interface. This way the nested class definition can stay hidden:
public class Outer
{
private class Nested : IFace
{
public Nested(...)
{
}
//interface member implementations...
}
public IFace GetNested()
{
return new Nested();
}
}
If you need to meet one of the following requirements:
You want the nested class to be sealed,
You don't want to copy all the nested class's method signatures to an interface like in Lee's answer,
I found a solution similar to the one posted by ak99372, but without using a static initializer:
public class Outer
{
private interface IPrivateFactory<T>
{
T CreateInstance();
}
public sealed class Nested
{
private Nested() {
// private constructor, accessible only to the class Factory.
}
public class Factory : IPrivateFactory<Nested>
{
Nested IPrivateFactory<Nested>.CreateInstance() { return new Nested(); }
}
}
public Nested GetNested() {
// We couldn't write these lines outside of the `Outer` class.
IPrivateFactory<Nested> factory = new Nested.Factory();
return factory.CreateInstance();
}
}
The idea is that the Nested class's constructor is accessible only to the Factory class, which is nested one level deeper. The Factory class explicitly implements the method CreateInstance from the private interface IPrivateFactory, so that only those who can see IPrivateFactory can call CreateInstance and get a new instance of Nested.
Code outside the Outer class can't freely create instances of Nested without asking Outer.GetNested(), because
Outer.Nested's constructor is privated, so they can't call it directly
Outer.Nested.Factory can be instantiated, but can't be cast to IPrivateFactory, so its CreateInstance() method can't be called.
Note that I wouldn't recommend using that pattern heavily in production code, but it's a trick I find useful to have up my sleeve on rare occasions.
In short, no, you cannot do that. There is an accessibity modifier "public" which means "accessible by anything inside me or outside me" and there is an accessibility modifier "private" which means "accessible by anything inside me". There is no modifier which means "accessible to the thing immediately outside me but not to anything outside it", which is what you would need to mark the constructor as. That's simply not a concept that the designers of the type system thought would be useful.
Can you describe why you want this crazy kind of accessibility? Perhaps there is a better way to get what you want.
Since there is nothing in C# syntax you'll have to implement something like "a contract" between them. You can take advantage of the fact that nested class can access private fields of its parent:
public class ParentClass
{
private static Func<FriendClass> _friendContract;
public class FriendClass
{
static FriendClass()
{
_friendContract= () => new FriendClass();
}
private FriendClass() { }
}
///Usage
public FriendClass MethodUse()
{
var fInstance = _friendContract();
//fInstance.DoSomething();
return fInstance;
}
}
Of course you can adjust the contract to handle different parameters
private static Func<Arg1,Arg2,FriendClass> _friendContract;
For the answer proposed by Joshua Smith I found it necessary to force the static constructor of FriendClass to run, achieved by calling an empty static Initalize() method on FriendClass from the static constructor of ParentClass.
With the new static abstract interface members of C# 11 you can limit the instantiation of nested classes quite neatly:
public class Outer
{
protected interface INestedFactory<T> where T : INestedFactory<T>
{
public static abstract T CreateInstance();
}
public class SomeNested : INestedFactory<SomeNested>
{
private SomeNested() { }
static SomeNested INestedFactory<SomeNested>.CreateInstance()
{
return new SomeNested();
}
}
protected void CreateNested<T>() where T : INestedFactory<T>
{
T.CreateInstance();
}
}
public class Outer
{
public class Nested
{
readonly Outer Outer;
public Nested(Outer outer /* , parameters */)
{
Outer = outer;
// implementation
}
// implementation
}
public Nested GetNested(/* parameters */) => new Nested(this /* , parameters */);
}
Note that you can access private members of Outer from Nested.

Private inner classes in C# - why aren't they used more often?

I am relatively new to C# and each time I begin to work on a C# project (I only worked on nearly mature projects in C#) I wonder why there are no inner classes?
Maybe I don't understand their goal. To me, inner classes -- at least private inner classes -- look a lot like "inner procedures" in Pascal / Modula-2 / Ada : they allow to break down a main class in smaller parts in order to ease the understanding.
Example : here is what is see most of the time :
public class ClassA
{
public MethodA()
{
<some code>
myObjectClassB.DoSomething(); // ClassB is only used by ClassA
<some code>
}
}
public class ClassB
{
public DoSomething()
{
}
}
Since ClassB will be used (at least for a while) only by ClassA, my guess is that this code would be better expressed as follow :
public class ClassA
{
public MethodA()
{
<some code>
myObjectClassB.DoSomething(); // Class B is only usable by ClassA
<some code>
}
private class ClassB
{
public DoSomething()
{
}
}
}
I would be glad to hear from you on this subject - Am I right?
Nested classes (probably best to avoid the word "inner" as nested classes in C# are somewhat different to inner classes in Java) can indeed be very useful.
One pattern which hasn't been mentioned is the "better enum" pattern - which can be even more flexible than the one in Java:
public abstract class MyCleverEnum
{
public static readonly MyCleverEnum First = new FirstCleverEnum();
public static readonly MyCleverEnum Second = new SecondCleverEnum();
// Can only be called by this type *and nested types*
private MyCleverEnum()
{
}
public abstract void SomeMethod();
public abstract void AnotherMethod();
private class FirstCleverEnum : MyCleverEnum
{
public override void SomeMethod()
{
// First-specific behaviour here
}
public override void AnotherMethod()
{
// First-specific behaviour here
}
}
private class SecondCleverEnum : MyCleverEnum
{
public override void SomeMethod()
{
// Second-specific behaviour here
}
public override void AnotherMethod()
{
// Second-specific behaviour here
}
}
}
We could do with some language support to do some of this automatically - and there are lots of options I haven't shown here, like not actually using a nested class for all of the values, or using the same nested class for multiple values, but giving them different constructor parameters. But basically, the fact that the nested class can call the private constructor gives a lot of power.
The Framework Design Guidelines has the best rules for using nested classes that I have found to date.
Here's a brief summary list:
Do use nested types when the relationship between type and nested type is such the member-accessibility semantics are desired.
Do NOT use public nested types as a logical group construct
Avoid using publicly exposed nested types.
Do NOT use nested types if the type is likely to be referenced outside of the containing type.
Do NOT use nested types if they need to be instantiated by client code.
Do NOT define a nested type as a member of an interface.
You should limit the responsibilities of each class so that each one stays simple, testable and reusable. Private inner classes go against that. They contribute to the complexity of the outer class, they are not testable and they are not reusable.
For me personally I only create private inner classes if I need to create in-process collections of an object that may require methods on them.
Otherwise, it could cause confusion for other developers working on the project to actually find these classes, as they are not very clear as to where they are.

Categories

Resources