C# base() constructor order [duplicate] - c#

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
C# constructor execution order
class Foo
{
public int abc;
Foo()
{
abc = 3;
}
}
class Bar : Foo
{
Bar() : base()
{
abc = 2;
}
}
In the example above, when an object of Bar is created, what will be the value of BarObject.abc? Is the base constructor called first, or is Bar() run, /then/ the base() constructor?

It'll be 2. Constructors run in order from base class first to inherited class last.
Note that initialisers (both static and instance variables) run in the opposite direction.
The full sequence is here: http://www.csharp411.com/c-object-initialization/

First base class constructor is called followed by the derived class constructor.
The result is 2. You should explicitly state the accessibility of that class variable.
Is it protected, private or public?
I see you changed it to public now, so it will be 2.
This link will further help you understand constructors, how they are used, when they are called, and order of constructor call when you use inheritance:
http://www.yoda.arachsys.com/csharp/constructors.html
Also you may want to actually try this out yourself, you will learn more by practicing and writing code then just reading it.
Try to declare Bar and output its value. Use some properties:
class Foo
{
public int abc;
public Foo()
{
abc = 3;
}
public int ABC
{
get { return abc; }
set { abc = value; }
}
}
class Bar : Foo
{
public Bar() : base()
{
abc = 2;
}
}
class Program
{
static void Main(string[] args)
{
Bar b = new Bar();
Console.WriteLine(b.ABC);
Console.ReadLine();
}
}
A simple printout would yield the result you are looking for. Here is the output:
Don't you just love my namespace :-). By the way you could also use automatic properties so that the property is simply public int ABC {get;set;}.

Assuming you make abc protected so that this compiles, it will be 2; however, base() is called first.
For stuff like this, write a simple test application and setup some breakpoints to find the answer.

The variable abc will be set to be 3 and then changed to be 2 (the base constructor is called first).

The base constructor will be called first, but this code does not compile. Private fields are not accesable from sub-classes. At the very least a field must be protected to be used in a sub-class.
But even knowing this, the behaviour you are attempting is confusing because it is surprising. Just the fact you had to ask which order things go in implies that it will get messed up when the order is forgotten.

The base constuctor is called first, and you would have a value of 2 for abc

Related

How can I ensure that a class has just 1 constructor in .NET?

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.

C# constructor execution order

In C#, when you do
Class(Type param1, Type param2) : base(param1)
is the constructor of the class executed first, and then the superclass constructor is called or does it call the base constructor first?
The order is:
Member variables are initialized to default values for all classes in the hierarchy
Then starting with the most derived class:
Variable initializers are executed for the most-derived type
Constructor chaining works out which base class constructor is going to be called
The base class is initialized (recurse all of this :)
The constructor bodies in the chain in this class are executed (note that there can be more than one if they're chained with Foo() : this(...) etc
Note that in Java, the base class is initialized before variable initializers are run. If you ever port any code, this is an important difference to know about :)
I have a page with more details if you're interested.
It will call the base constructor first. Also keep in mind that if you don't put the :base(param1) after your constructor, the base's empty constructor will be called.
The constructor of the baseclass is called first.
Not sure if this should be a comment/answer but for those who learn by example this fiddle illustrates the order as well: https://dotnetfiddle.net/kETPKP
using System;
// order is approximately
/*
1) most derived initializers first.
2) most base constructors first (or top-level in constructor-stack first.)
*/
public class Program
{
public static void Main()
{
var d = new D();
}
}
public class A
{
public readonly C ac = new C("A");
public A()
{
Console.WriteLine("A");
}
public A(string x) : this()
{
Console.WriteLine("A got " + x);
}
}
public class B : A
{
public readonly C bc = new C("B");
public B(): base()
{
Console.WriteLine("B");
}
public B(string x): base(x)
{
Console.WriteLine("B got " + x);
}
}
public class D : B
{
public readonly C dc = new C("D");
public D(): this("ha")
{
Console.WriteLine("D");
}
public D(string x) : base(x)
{
Console.WriteLine("D got " + x);
}
}
public class C
{
public C(string caller)
{
Console.WriteLine(caller + "'s C.");
}
}
Result:
D's C.
B's C.
A's C.
A
A got ha
B got ha
D got ha
D
[Edit: in the time it took me to answer, the question had totally changed].
The answer is that it calls the base first.
[Original answer to the old question below]
Are you asking when you would do the "base" bit of the constructor call?
If so, you would "chain" a call to the constructor base if the class is derived from another class which has this constructor:
public class CollisionBase
{
public CollisionBase(Body body, GameObject entity)
{
}
}
public class TerrainCollision : CollisionBase
{
public TerrainCollision(Body body, GameObject entity)
: base(body, entity)
{
}
}
In this example, TerrainCollision derives from CollisionBase. By chaining the constructors in this way, it ensures the specified constructor is called on the base class with the supplied parameters, rather than the default constructor (if there is one on the base)
Your question is a bit unclear but I'm assuming you meant to ask the following
When to I call the base constructor for my XNA object vs. using the impilict default constructor
The answer to this is highly dependent on both your scenario and the underlying object. Could you clarify a bit wit the following
What is the scenario
What is the type of the base object of TerrainCollision?
My best answer though is that in the case where you have parameters that line up with the parameters of the base class`s constructor, you should almost certainly be calling it.
Constructor mechanism is much better as it leaves the application to use constructor chaining and if you were to extend the application it enables through inheritance the ability to make minimal code changes.
Jon Skeets Article

How to create a constructor that is only usable by a specific class. (C++ Friend equivalent in c#)

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.

What are the best practices for Private Member Instantiation/Initialization? [duplicate]

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();
}
}

C#: Can a base class use a derived class's variable in a static function?

Is there anyway of having a base class use a derived class's static variable in C#? Something like this:
class Program
{
static void Main(string[] args)
{
int Result = DerivedClass.DoubleNumber();
Console.WriteLine(Result.ToString()); // Returns 0
}
}
class BaseClass
{
public static int MyNumber;
public static int DoubleNumber()
{
return (MyNumber*2);
}
}
class DerivedClass : BaseClass
{
public new static int MyNumber = 5;
}
I'm trying to have it return 10, but I'm getting 0.
Here's where I'm using this: I have a class called ProfilePictures with a static function called GetTempSavePath, which takes a user id as an argument and returns a physical path to the temp file. The path base is a static variable called TempPath. Since I'm using this class in multiple projects and they have different TempPaths, I'm creating a derived class that sets that variable to whatever the path is for the project.
See Also
Why can’t I declare C# methods virtual and static?
Apart from the fact that has already been pointed out... that static variables are tied or bound to the specific class declaring them and cannot be overridden. Overriding/Polymorphism needs instances to work.
Your problem can be solved with a change in design.
string ProfilePictures.GetTempSavePath(SomeType UserId, string sBasePath)
if it just needs these 2 variables to compute the return value, you can keep it as a utility/static method. Now you can feed in different base paths..
Now it seems from your question, that you need to use this class in multiple projects (which have fixed base paths) and kind of hardcode the base path so that you dont have to specify it for each call.
Type/Class hierarchies should be defined based on behavior and not on data. Variables can handle change in data. Hence I'd suggest holding the basepath value as a static member variable, which is initialized from a resource file (DoubleClick your project properties node > Settings > Add a new Settings file > add a new setting called BasePath - string - Application scope - VALUE=C:\Users). Now you just need to tweak the app.config file for each project, no code changes, no hardcoding and not more than one type needed.
public class PathHelper
{
static string _sBasePath;
static PathHelper()
{
_sBasePath = Properties.Settings.Default.BasePath;
}
static string GetTempSavePath(string sUserId)
{
// dummy logic to compute return value, replace to taste
return Path.Combine(_sBasePath, sUserId.Substring(0, 4));
}
}
Hope that made sense
The problem is that you're re-declaring the static variable in the derived class. The MyNumber declaration in DerivedClass hides the declaration in the base class. If you remove that declaration, then references to the "MyNumber" in derived class static functions will refer to the base class variable. Of course, if you remove the declaration then you can't use a static initializer in the derived class.
You might want to consider requiring users to instantiate an instance of ProfilePictures rather than provide a static function for GetTempSavePath. That way you could overide the GetTempSavePath method to provide the correct TempPath. Or, you could simply set the value of the static path value in your derived class constructor.
Although it is possible to use inheritance with static members, you can't relly have polymorphic behavior without a "this" pointer.
Static members are not virtual, so you can not override them.
When you call DerivedClass.DoubleNumber you are actually calling BaseClass.DoubleNumber as the DerivedClass class doesn't have that method. Also, the use of MyNumber in that method is always going to be BaseClass.MyNumber no matter how you call the method.
What you are looking for is a virtual property that you can override in a derived class. As a virtual member can not be static, you need to use an instance of the class. If it's not practical to keep a reference to the instance, you can use the singleton pattern.
This kinda works:
public class ClassA
{
protected static int num = 5;
public static int GetNum()
{
return num;
}
}
public class ClassB : ClassA
{
static ClassB()
{
num = 6;
}
}
However, note the difference when you call ClassB.GetNum() before and after instantiating one object. The static initializer doesn't run until you create at least one, so you'll get 5 if nothing has been created, and 6 if at least one object has.
Provide a virtual method that returns the class static.
class BaseClass
{
public virtual int GetMyNumber() { return MyNumber; }
}
You might want to use a virtual property instead...
Using too much of static members is also not recommended if they are going to encapsulate a logic of an entire object. For example your code can be rewritten correctly in following manner... and this is the most recommended in oops,
class Program
{
static void Main(string[] args)
{
int Result = DerivedClass.Instance.DoubleNumber();
Console.WriteLine(Result.ToString()); // Returns 0
}
}
class BaseClass
{
protected BaseClass(){} // this enforces that it can not be created
public int MyNumber;
public virtual int DoubleNumber()
{
return (MyNumber*2);
}
}
public class DerivedClass : BaseClass
{
// this also ensures that it can not be created outside
protected DerivedClass(){
MyNumber = 5;
}
// only way to access this is by Instance member...
public static DerivedClass Instance = new DerivedClass();
}
This is how we access configuration values and many other single instance static objects provided by .Net Library.

Categories

Resources