Difference in instancing object - C# basic [duplicate] - c#

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.

Related

Derived constructor with type parameter

EDIT: added follow up question from getting a solution suggested from another question
EDIT2: I just realised that my follow up question was not needed.
Is it possible to have an abstract base class with a type parameter of T have a constructor that takes a parameter of T and assigns it to a property of T? What i want to achieve is that all derived classes has a constructor that does this?
Something like:
public abstract class NotificationBase <T>
{
public string Text { get; set; }
public T Context { get; set; }
public NotificationBase(T context, string text)
{
Context = context;
Text = text;
}
}
public class NumberNotification : NotificationBase<int>{}
public class Program
{
public void Run()
{
var thing = new NumberNotification(10, "Hello!");
}
}
EDIT:
I got a link to another question that explained how to do this which is great. However i have some issues with that. And i dont mean its wrong, if that is the only way to do it then thats how it is. However its not the ideal situation for what im trying to do. I explain. This was the solution:
public class Base
{
public Base(Parameter p)
{
Init(p)
}
void Init(Parameter p)
{
// common initialisation code
}
}
public class Derived : Base
{
public Derived(Parameter p) : base(p)
{
}
}
..which works great. However it does create two small issues that id like to se if they can be addressed.
What i want is to force all classes that derives from the base to pass a T into the constructor so that its mandatory. With this solution, its possible to leave it out.
If all classes should do this then it feels redundant to create a constructor to propagate a mandatory parameter.
EDIT: I just realised that demanding a constructor that propagates the type parameter IS what im looking for. I makes sure that the T property gets a value and also allows for other things to happen in the constructor.
Yes, you can, you just need to propagate the constructor chain using the relevant type, and call the ancestor if needed:
public class NumberNotification : NotificationBase<int>
{
public NumberNotification(int context, string text)
: base(context, text)
{
}
}
Without constructor in child class, the instantiation you wrote can't compile because you don't offer a way for the compiler to know what to do.
You can also offer any other constructor needed.
Therefore now this compiles and works:
var thing = new NumberNotification(10, "Hello!");
Inheritance And Constructors (C# Corner)
base (C# Reference)
Define the parameterized constructor for NumberNotification class which should invoke the required constructor of NotificationBase using base
public class NumberNotification : NotificationBase<int>
{
public NumberNotification(int context, string text)
:base(context, text)
{
}
}
Now for NumberNotification object, context is type of int as here T is marked as int type which Yyou can check using below code:
var thing = new NumberNotification(10, "Hello!");
Console.WriteLine(thing.Context.GetType());
The above prints the output as System.Int32
Check the fiddle - https://dotnetfiddle.net/keufQO

Methods for Lazy Initialization with properties

I'm currently altering a widely used class to move as much of the expensive initialization from the class constructor into Lazy Initialized properties. Below is an example (in c#):
Before:
public class ClassA
{
public readonly ClassB B;
public void ClassA()
{
B = new ClassB();
}
}
After:
public class ClassA
{
private ClassB _b;
public ClassB B
{
get
{
if (_b == null)
{
_b = new ClassB();
}
return _b;
}
}
}
There are a fair few more of these properties in the class I'm altering, and some are not used in certain contexts (hence the Laziness), but if they are used they're likely to be called repeatedly.
Unfortunately, the properties are often also used inside the class. This means there is a potential for the private variable (_b) to be used directly by a method without it being initialized.
Is there a way to make only the public property (B) available inside the class, or even an alternative method with the same initialized-when-needed?
This is reposted from Programmers (not subjective enough apparently):
https://softwareengineering.stackexchange.com/questions/34270/best-methods-for-lazy-initialization-with-properties
Well, my recommended solution would be to tell your coworker to use the property, not the field. But you could idiot-proof it to some degree like this:
public class ClassA
{
private Lazy<ClassB> _b = new Lazy<ClassB>(() => new ClassB());
public ClassB B
{
get
{
return _b.Value;
}
}
}
Now it's pretty hard to screw up.
You could consider pushing the lazy properties into a base class to avoid direct access to the backing variable. Not ideal I know. I've always thought this was something lacking in C# i.e. direct support for lazy properties.
#chibacity posted (and subsequently) deleted [and later undeleted :P] an alternative option using an abstract base class. While it may not be ideal in terms of code distribution it does provide a nice encapsulation removing a lot of code clutter making for a cleaner and more succinct ClassA. For instance, you could consider combining the techniques to achieve both goals:
public class ClassB { /* Class to be lazily instantiated */ }
public abstract class BaseA
{
private Lazy<ClassB> _b = new Lazy<ClassB>(() => new ClassB());
public virtual ClassB B { get { return _b.Value; } }
}
public class ClassA : BaseA
{
public override ClassB B { get { return base.B; } }
}
At first glance, it seems like this is more long winded, but when you consider that ClassA which is the class you would be working in and with, this now means that all your references are going through the same property - there is no extraneous unnecessary field causing potential confusion, there's no bypassing the property to reference _b directly and there's no need to tell your coworker which to use... there's only one.
Not saying this is the right way to do this or that this is a pattern that should or shouldn't be followed, I'm just pointing out the advantages of what #chibacity suggested that may otherwise go unnoticed.
It would be nice if you could have implicit lazy loaded properties without having to refer to B.Value... for instance:
[Lazy]
public ClassB B { get; }
or for objects without parameterless constructors
[Lazy(() => new ClassB("Hello", "World"))]
public ClassB B { get; }
or perhaps as #chibacity suggested in a comment
public ClassB B { lazyget; }
or
public ClassB B { lazyget : new ClassB(); }
Alas, I don't think any of these are currently available solutions in any form...

Private constructor and public parameter constructor

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

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

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