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.
Related
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>.
This is my class how hold my last visited Path:
public class LastPath
{
private static string _lastPath;
public static string lastPath
{
get { return _lastPath; }
set { _lastPath = value; }
}
}
If all members of a class is static and your class is not meant to instantiated it should be static.
In this case your class satisfies the above rule or guideline so marking it as static will make sense because you don't have any instance member.
LastPath path = new LastPath();
path.????// Nothing to access, so prevent instantiation by marking class static.
Being said that If you have only one field in your class and no methods I'd argue that you probably don't need a class at all, just refactor it to some other class where it would make sense.
make the class static and make a public property as static and you are done, like this:
public static class LastPath
{
public static string lastPath { get;set;}
}
I would say you to do this:
public static class LastPath
{
public static string lastPath
{
get;set;
}
}
You should declare it as static as static classes cannot be instantiated, while non static classes can be instantiated, which is not needed.
First - it looks odd to me to create class for holding single variable. Consider to use simple string variable lastVisitedPath instead. If you use this variable in single class, then make it field of that class.
Second - naming is not very readable. Here is how getting last path looks like: LastPath.lastPath. You see this useless duplication? Also keep in mind, that due to Microsoft naming guidelines public members should have Pascal Case names. Consider to create class with descriptive name like GlobalValues or Cache which reflects its purpose:
public static class GlobalValues // holds values which are globally accessible
{
public static string LastVisitedPath;
// other global values
}
So that usage will look like GlobalValues.LastVisitedPath or Cache.LastVisitedPath. Of course, if these classes don't supposed to be instantiated, they should be static.
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();
}
}
}
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.
I have a generic class definition similar to this:
public sealed class MyClass<TProperty,TOwner>
{
...
}
Now I'd like any instances of MyClass<TProperty,TOwner> regardless of the types of TProperty or TOwner to share a Hashtable. I thought of creating an internal MyClassBase with a protected internal static field of type Hashtable and inherit from that. I really only want the definition of MyClass to have access to this hashtable.
Is this a sound approach? I can't seal MyClassBase, so this probably could lead to opening a can of worms later on...
Are there other approaches for this?
The protected static Hashtable is a fine approach (make sure you synchronize it). You can't have an internal base class whose derived classes are public - but you can prevent it from being derived outside your assembly by making its default constructor internal:
public abstract class MyBaseClass
{
internal MyBaseClass() { }
private static Hashtable _hashtable;
protected static Hashtable Hashtable
{
get
{
if(_hashtable == null)
{
_hashtable = Hashtable.Synchronized(new Hashtable());
}
return _hashtable;
}
}
}
Another option is to make an internal static class with an exposed member, and only access it from MyClass<T,U>. Sure, it'd be visible within your assembly, but that's easily controlled compared to a protected member. Just make sure to only use it in your MyClass<T,U> and it'll be fine.