This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
C# member variable initialization; best practice?
Is there any benefit to this:
public class RemotingEngine
{
uint m_currentValueId;
object m_lock;
public RemotingEngine()
{
m_currentValueId = 0;
m_lock = new object();
}
vs. this:
public class RemotingEngine
{
uint m_currentValueId = 0;
object m_lock = new object();
I have been avoiding the second one just because it feels 'dirty'. It is obviously less typing so that is appealing to me.
It can make a difference in an inheritance situation. See this link on the object initialization order:
http://www.csharp411.com/c-object-initialization/
Derived static fields
Derived static constructor
Derived instance fields
Base static fields
Base static constructor
Base instance fields
Base instance constructor
Derived instance constructor
So if this is a derived class, the entire base object is initialized between when your derived field is initialized and when your constructor runs.
There's not a whole lot of difference, I'd keep with the first one because it's more readable. Usually variables are defined at the top of the class, and I can go there and check out their default values instead of hunting down a constructor and seeing if it sets it. As far as the compiler is concerned, there is no difference, unless you have multiple constructors.
I always use the first one for this reason: It's the responsibility of the constructor to initialize variables. Different constructors may initialize variables differently. So yes, you should feel dirty doing it the second way =).
I prefer the second and in some cases it depends on your coding standards. But consider the processing sequence:
target class field initialization -> base class field initialization -> base class constructor -> target class constructor
if the base class or target class has an exception creating the object and the fields are preinitialized it will have a value at finalization and may cause some unexpected problems.
See also this blog by Bill Simser Best Practices and Member Initialization in C#
For the int, you don't have to do it at all, intrinsic types are initialized to default() - which, for int's is 0.
As for object, it's a matter of taste imo. I prefer the former. If someone is overriding my constructor, I expect them to call base() to construct it in a proper state.
you want to avoid instantiation outside of scope of your constructor given that it shows intent and especially if you are overriding constructors you have a bit more flexibility
They are identical as far as the IL is concerned.
The compiler turns this:
class Foo
{
int bar = 1;
}
into this:
class Foo
{
int bar;
public Foo()
{
this.bar = 1;
}
}
Even if you add a constructor yourself like this:
class Foo
{
int bar = 1;
public Foo(int bar)
{
this.bar = bar;
}
}
The compiler turns it into this:
class Foo
{
int bar;
public Foo(int bar)
{
this.bar = 1;
this.bar = bar;
}
}
I have a different take on this. I think you should abstract to properties and set them in the constructor. Using automatic properties would basically eliminate the question since you aren't able to initialize them (to anything other than the default).
public class RemotingEngine {
private uint CurrentValueID { get; set; }
private object Lock { get; set; }
public RemotingEngine()
{
this.CurrentValueID = 0; // not really necessary...
this.Lock = new object();
}
}
Related
This question already has answers here:
Initialize class fields in constructor or at declaration?
(16 answers)
Closed 10 years ago.
I am beginner in object oriented programming and I have one simple question. What is difference between:
public class Calculation
{
private _externalObject = new ExternalClass();
public int FirstParameter {get;set;}
public int SecondParameter {get;set;}
public int ThirdParameter {get;set;}
public int FourthParameter
{
get
{
_externalObject.Calculate(FirstParameter, SecondParameter, ThirdParameter);
}
}
}
and
public class Calculation
{
private _externalObject;
public Calculation()
{
_externalObject = new ExternalClass();
}
public int FirstParameter {get;set;}
public int SecondParameter {get;set;}
public int ThirdParameter {get;set;}
public int FourthParameter
{
get
{
_externalObject.Calculate(FirstParameter, SecondParameter, ThirdParameter);
}
}
}
I want to learn how should I write optimal code.
In this particular case, there isn't any measurable difference.
If, however, you had more than one constructor, you would have to initialize the field in each constructor if you didn't do it directly in the field declaration.
It is more a matter of personal style than anything.
Note on class design and integration - if you have an external dependency like that, good OOP would require you to use DI (Dependency Injection) instead of instantiating the value within the class directly. Constructor injection is a good choice:
private ExternalClass _externalObject;
public Calculation(ExternalClass externalClass)
{
_externalObject = externalClass;
}
The above allows for modification of behaviour without changing the actual class and makes the class more testable.
In this case, those two classes are identical. In fact, for almost all purposes, the two styles of code you used are the same. In general, you will find that most style guides recommend using the field initializers (this is particularly true of static field initializers).
There is one subtle difference, but it's very unlikely that it will ever affect you.
Whenever you initialize class members inline, C# generates code to perform that initialization just before it runs any code in the constructor. In particular, if your constructor calls into a base class constructor. Field initializers are run before the base class constructor is called, while the code in your user-supplied constructor must be run afterward. That is, the following two classes are slightly different:
public class B : A
{
// This happens *before* the base-class constructor.
public ExternalObject external = new ExternalObject();
public B () : base() { }
}
public class C : A
{
public ExternalObject external;
public C () : base()
{
// This happens *after* the base-class constructor.
this.external = new ExternalObject();
}
}
Note that, if you don't provide a default constructor, C# automatically provides one that calls into base() for you, making your class "look like" class B even if you don't explicitly provide the B() constructor.
In practice, the difference is unlikely to matter. You can't actually reference this in your field initializers, so you can't rely on the base class being constructed in either case.
Well my question is pretty self-explanatory. I have a class and I want to ensure that there is just 1 public constructor to this class. Moreover, I also want to ensure that the constuctor should have just 1 parameter. My class will be modified by many different developers, and I am looking for a way to ensure that they do not write any more constructors than are currently specified. Is it possible? If yes, then how?
Note, my class inherits from another class which currently does not have any constructor but it might have in the future. I don't know if this information will affect the answer or not but just thought of adding it.
Please help!
Thanks in advance!
You could consider writing a unit test to encode this design constraint. As long as the test isn't fiddled with, this will warn when the contraint is broken.
This would be a good case for a nice comment in your class detailing this constraint.
The following testing approach can be expanded to provide a test which could test derived types, rather than a single type. This approach is a type of static analysis, and removes the overhead that would be incurred by expensive runtime checking through reflection for instance. A test ensures that the design constraint is validated at build time, rather than at runtime which could be after code is released.
[Test]
public void myClass_must_have_one_single_paramter_ctor()
{
Type type = typeof(MyClass);
const BindingFlags Flags = (BindingFlags.Public | BindingFlags.Instance);
ConstructorInfo[] ctors = type.GetConstructors(Flags);
Assert.AreEqual(1, ctors.Length, "Ctor count.");
ParameterInfo[] args = ctors[0].GetParameters();
Assert.AreEqual(1, args.Length, "Ctor parameter count.");
Assert.AreEqual(typeof(string), args[0].ParameterType, "Ctor parameter type.");
}
public class MyClass
{
public MyClass(string woo) {}
}
All classes have one constructor. If you don't specify one in the source code, the compiler will add an empty public constructor - the equivalent of:
public class MyClass
{
public MyClass()
{
}
}
However if you specify at least one constructor in the source, only the constructors that you explicitly specify will be created, e.g. the following class has one public constructor that takes a single string parameter:
public class MyClass
{
public MyClass(string myParameter)
{
...
}
}
In short, there's nothing special you need to do. If you only want one public constructor then ... just write one public constructor.
Only the person who codes the class can restrict the number and type of constructors.
So if that is you, then you can just code it the way you want.
This could be achieved using reflection. The only thing you need to take care is, the base class code shouldn't be accessible to or editable by developers.
class Program
{
static void Main(string[] args)
{
Inherited obj = new Inherited("Alpha");
obj.test();
Inherited1 obj1 = new Inherited1(); //This will fail as there is no ctor with single param.
obj1.test();
}
}
public class MyBase
{
private static IList<string> ValidatedClasses = new List<string>();
public MyBase()
{
if(!ValidatedClasses.Contains(this.GetType().FullName) &&
!ValidateConstructorLogic())
{
throw new ApplicationException("Expected consturctor with single argument");
}
}
public bool ValidateConstructorLogic()
{
bool ValidConstFound = false;
foreach (var info in this.GetType().GetConstructors())
{
if(info.GetParameters().Length ==1)
{
lock (ValidatedClasses)
{
ValidatedClasses.Add(this.GetType().FullName);
}
ValidConstFound = true;
}
}
return ValidConstFound;
}
}
public class Inherited:MyBase
{
public Inherited(string test)
{
Console.WriteLine("Ctor");
}
public void test()
{
Console.WriteLine("TEST called");
}
}
public class Inherited1 : MyBase
{
public void test()
{
Console.WriteLine("TEST called");
}
}
You could use FxCop to validate your code against a set of predefined rules. I beleive this might be the apt solution to your problem. If you need help on creating custom FxCop rules, please refer this article.
Constructors are not inherited from base classes.
Your class will have only the constructors that you write, except for (as others have pointed out) a default public constructor that is generated by the compiler when you do not explicitly provide one of your own.
You could try using a nested builder, as described by Jon Skeet. Basically: You force the user to go through the builder which then calls the private class constructor. Since the class constructor is private, only the nested builder has access to it.
Alternative: Use static factory methods, make the constructor private & document your intentions.
Based on your comments, I don't think this is a "coding" problem. This is a policy & enforcement problem. You don't want other developers in your team creating more constructors.
In that case, go tell them that. Whoever is in charge of your source code repository can enforce it by rejecting changes that break the policy. Adding code to deal with this is just going to add runtime penalties to users for no reason.
I heard that a private constructor prevents object creation from the outside world.
When I have a code
public class Product
{
public string Name { get;set;}
public double Price {get;set;}
Product()
{
}
public Product(string _name,double _price)
{
}
}
Here I still can declare a public constructor (parameter), won't it spoil the purpose of the private constructor? When do we need both private and public constructor (parameter) in code?
I need a detailed explanation please.
The reason you would use the pattern you're describing is when you want to control how the object is instantiated.
In your example, for instance, you're saying the only way to create a Product is by specifying its name and price. This is with respect to the outside world, of course. You could also do something similar using other access modifiers, and it would have different implications, but it all boils down to controlling how you want the objects instantiated with respect to who will be doing it.
If you wanted to prevent object creation altogether you would have to make all your constructors private (or protected). That would force the object to be created from within itself (or an inherited class).
Also, as Matti pointed out in the comment below, when you define a constructor that is parameterized you don't need to specify a private default constructor. At that point it is implied.
Constructors can be chained together to avoid having to duplicate code. It is quite common to have private constructors, that nobody is supposed to call outside of the class, that are chained from a public constructor.
Example:
public class Test
{
private Test(int? a,string b) { }
public Test(int a) : this(a, null) { }
public Test(string b) : this(null, b) { }
}
Here there are two public constructors, one taking a string and one taking an int. They both chain to the common private constructor that takes both arguments.
Also, you can construct new objects from within the same class by using the private constructor. For instance, when you want specialized constructors only available through static factory methods:
public static Test Create()
{
int? a = ReadConfigurationForA();
string b = ReadConfigurationForB();
return new Test(a, b);
}
When it is not be a good idea to expose a private constructor to the outside world, add a static factory method that fetches the correct arguments to pass on the constructor.
You need a private constructor when you only want that constructor to be called from within the class itself. In your example you are forcing the calling object to provide 2 parameters when creating the object.
With a private constructor you could do something like:
public static GetInstance ()
{
return new YourObject();
}
but nothing else except the object could call the parameterless constructor.
It's commonly used to create a singleton pattern:
http://www.dofactory.com/Patterns/PatternSingleton.aspx
You would use a constructor with parameters when you wanted to force calling code to pass a value to the constructor in order to create an instance of your class. In your example, calling code must use the parameter version of the constructor in order to create a Product.
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
For more details refer to this:
http://msdn.microsoft.com/en-us/library/kcfb85a6(VS.80).aspx
As far as I know, in C#, there is no support for the "friend" key word as in C++. Is there an alternative way to design a class that could achieve this same end result without resorting to the un-available "friend" key-word?
For those who don't already know, the Friend key word allows the programmer to specify that a member of class "X" can be accessed and used only by class "Y". But to any other class the member appears private so they cannot be accessed. Class "Y" does not have to inherit from class "X".
No, there is no way to do that in C#.
One common workaround is to based the object for which you want to hide the constructor on an interface. You can then use the other object to construct a private, nested class implementing that interface, and return it via a Factory. This prevents the outside world from constructing your object directly, since they only ever see and interact with the interface.
public interface IMyObject
{
void DoSomething();
}
public class MyFriendClass
{
IMyObject GetObject() { return new MyObject(); }
class MyObject : IMyObject
{
public void DoSomething() { // ... Do something here
}
}
}
This is how I solved it. I'm not sure if it's the "right" way to do it, but it required minimal effort:
public abstract class X
{
// "friend" member
protected X()
{
}
// a bunch of stuff that I didn't feel like shadowing in an interface
}
public class Y
{
private X _x;
public Y()
{
_x = new ConstructibleX();
}
public X GetX()
{
return _x;
}
private class ConstructibleX : X
{
public ConstructibleX()
: base()
{}
}
}
No. The closest you have is an internal constructor, or a private constructor and a separate factory method (probably internal, so you haven't saved much).
What about just having it explicity implement an interface that is only visible to a certain class?
Something like:
public void IFreindOfX.Foo() //This is a method in the class that's a 'friend' to class X.
{
/* Do Stuff */
}
and then make sure IFriendOfX is visible to class X. In your X class you'd call the method by first casting X to IFriendOfX then calling Foo(). Another advantage is that is is fairly self documenting... that is, it's pretty close to having the friend keyword itself.
What about creating a private class? This does exactly what you seem to be describing. A member of class X can be accessed and used only by class Y, and to any other class it appears private, since, well, it is private:
public class Y
{
private class X { }
private X Friend;
public Y()
{
Friend = new X();
}
}
As far as I know, the Internal keyword is the closest thing in .NET. This question will shed more light on Internal: Internal in C#
The only thing I can think of that would even come close would be protected internal but that does not restrict it to a specific class. The only friending I'm aware of in c# is to make a friend assembly. Still does not restrict to a specific class.
The only thing I could think of to try and do it would be to do something like the following:
public class A
{
public A() {}
protected internal A(B b) {}
}
public class B
{
A myVersion;
public B()
{
myVersion = A(this);
}
}
The only other way I could think of would be to do some sort of Constructor Injection using reflection that is done inside of your friend class. The injection mechanism would allow you to limit it to what you want but could be very cumbersome. Take a look at something like Spring.Net for some injection capabilities.
As a workaround, I suppose you could create a conditional in your constructor that uses reflection.
For example, if Class1's constructor must be called by Class2:
public Class1()
{
string callingClass = new StackFrame(1).GetMethod().DeclaringType.Name;
if (callingClass != "Class2")
{
throw new ApplicationException(
string.Concat("Class1 constructor can not be called by ",
callingClass, "."));
}
}
EDIT:
Please note that I would never actually do this in "real" code. Technically it works, but it's pretty nasty. I just thought it was creative. :)
You can access private members/methods using Reflection.
Since it's got the design tag, I never particularly liked the friend keyword. It pierces encapsulation and that always felt dirty to me.
This has a bit of a smell. There are other plenty of other ways to achieve implementation hiding in C#. Limiting construction to only specific classes does not achieve all that much.
Could you please provide more information as to the purpose of this requirement? As already answered, internal is the closest match for limiting accessibility to the class. There are ways to build on top of that depending on the purpose.
I would like to force subclasses to implement the singleton pattern.
I originally thought of having an abstract static property in the parent class, but upon closer though, that didn't make sense (abstract requires and instance).
Next, I thought of having an interface with a static property, but that also doesn't make sense (interfaces also require an instance).
Is this something which is possible, or should I give up this train of thought and implement an abstract factory?
Please reconsider. You do NOT want to use singletons here. You are making some functionality available to users who derive from your class. That's fine. But you're also dictating one specific way in which it must always be used, and for absolutely no reason. That is not good.
It may make sense to only instantiate one object of this class the majority of the time, but in that case, simply just instantiate the object once. It's not like you're very likely to accidentally instantiate a dozen objects without noticing.
Moreover, how can you tell that having two instances will NEVER be useful? I can think of several cases even now.
Unit testing: You might want each test to instantiate this object, and tear it down again afterwards. And since most people have more than one unit test, you'll need to instantiate it more than once.
Or you might at some point decide to have multiple identical/similar levels in your game, which means creating multiple instances.
A singleton gives you two things:
A guarantee that no more than one instance of the object will ever be instantiated, and
Global access to that instance
If you don't need both these things, there are better alternatives.
You certainly don't need global access. (globals are bad, and usually a symptom of bad design, especially in mutable data such as your game state)
But you don't need a guarantee that no more than one instances will ever be instantiated either.
Is it the end of the world if I instantiate the object twice? Will the application crash? If so, you need that guarantee.
But in your case, nothing bad will happen. The person instantiating the object simply uses more memory than necessary. But he might have a reason.
Simply put in the class documentation that this is a very big and expensive class, and you shouldn't instantiate it more often than necessary. Problem solved. You don't remove flexibility that might turn out to be useful later on, you don't grant global access to data for no reason. Because you can control who can see the object, you don't need to drown it in locks that will become a bottleneck in multithreaded applications. You don't have hidden dependencies scattered throughout your code, making it harder to test and harder to reuse.
Try using an IOC container. Most good IOC containers enable the use of the singleton pattern without having to implement it yourself (ie: spring framework) - I like this better than forcing a static GetInstance() method.
Besides, it's not really possible in java, it would work in C++ with templates though.
Why? If someone wants to use multiple instances of a subclass of your class they might have a perfectly valid reason to.
If you want to do something that only should be done once for each class that subclasses your class (why, I have no idea, but you might have a reason to), use a Dictionary in the base class.
I would define a sealed class that gets its functionality from delegates passed to the constructor, something like this:
public sealed class Shape {
private readonly Func<int> areaFunction;
public Shape(Func<int> areaFunction) { this.areaFunction = areaFunction; }
public int Area { get { return areaFunction(); } }
}
This example does not make a lot of sense, it just illustrates a pattern.
Such a pattern cannot be used everywhere, but sometimes it helps.
Additionally, it can be extended to expose a finite number of static fields:
public sealed class Shape {
private readonly Func<int> areaFunction;
private Shape(Func<int> areaFunction) { this.areaFunction = areaFunction; }
public int Area { get { return areaFunction(); } }
public static readonly Shape Rectangle = new Shape(() => 2 * 3);
public static readonly Shape Circle = new Shape(() => Math.Pi * 3 * 3);
}
I think you will be better off with a factory pattern here to be honest. Or use an IoC tool like Brian Dilley recommends. In the c# world there are loads, here are the most popular : Castle/windsor, StructureMap, Unity, Ninject.
That aside, I thought it would be fun to have a go at actually solving your problem! Have a look at this:
//abstract, no one can create me
public abstract class Room
{
protected static List<Room> createdRooms = new List<Room>();
private static List<Type> createdTypes = new List<Type>();
//bass class ctor will throw an exception if the type is already created
protected Room(Type RoomCreated)
{
//confirm this type has not been created already
if (createdTypes.Exists(x => x == RoomCreated))
throw new Exception("Can't create another type of " + RoomCreated.Name);
createdTypes.Add(RoomCreated);
}
//returns a room if a room of its type is already created
protected static T GetAlreadyCreatedRoom<T>() where T : Room
{
return createdRooms.Find(x => x.GetType() == typeof (T)) as T;
}
}
public class WickedRoom : Room
{
//private ctor, no-one can create me, but me!
private WickedRoom()
: base(typeof(WickedRoom)) //forced to call down to the abstract ctor
{
}
public static WickedRoom GetWickedRoom()
{
WickedRoom result = GetAlreadyCreatedRoom<WickedRoom>();
if (result == null)
{
//create a room, and store
result = new WickedRoom();
createdRooms.Add(result);
}
return result;
}
}
public class NaughtyRoom :Room
{
//allows direct creation but forced to call down anyway
public NaughtyRoom() : base(typeof(NaughtyRoom))
{
}
}
internal class Program
{
private static void Main(string[] args)
{
//Can't do this as wont compile
//WickedRoom room = new WickedRoom();
//have to use the factory method:
WickedRoom room1 = WickedRoom.GetWickedRoom();
WickedRoom room2 = WickedRoom.GetWickedRoom();
//actually the same room
Debug.Assert(room1 == room2);
NaughtyRoom room3 = new NaughtyRoom(); //Allowed, just this once!
NaughtyRoom room4 = new NaughtyRoom(); //exception, can't create another
}
}
WickedRoom is a class that properly implements the system. Any client code will get hold of the singleton WickedRoom class. NaughtyRoom does not implement the system properly, but even this class can't be instantiated twice. A 2nd instantiation results in an exception.
Although this will not enforce the user to have a singleton subclass, you can enforce the user to create only one instance of the class (or its sub-classes) as below. This will throw error if a second instance of any subclass is created.
public abstract class SuperClass {
private static SuperClass superClassInst = null;
public SuperClass () {
if(superClassInst == null) {
superClassInst = this;
}
else {
throw new Error("You can only create one instance of this SuperClass or its sub-classes");
}
}
public final static SuperClass getInstance() {
return superClassInst;
}
public abstract int Method1();
public abstract void Method2();
}