What happen when new Instance of an object call? - c#

There is one confusion in my mind, about the constructor of class. How ever I tried to find this but doesn't find any answer relevant to my confusion..
Suppose I have a class
public class mySampleClass
{
public mySampleClass()
{
// This is the constructor method.
}
// rest of the class members goes here.
}
which have many properties, when I initialize this class what happen? I mean to say whether only constructor is being called? or something else?
what about rest of the properties? i am asking this foolish question because of my WCF service, which contain many methods, in every methods I have initialize same class, if I make object globally it crashes some where.
My other question is how many time it takes to initialize new instance of constructor? depending of all code? or whether constructor body?
Please elaborate with some Example. with two constructor or many.
UPDATE :
There is some confusion Regarding this Question, I have simply share one Scenario like WCF services, but I have to known all over constructor initialization Time, whether it depends on constructor? or all over object (containing other methods properties).
In simple words
I want to know constructor behaviour when it is initilize whether it is depend on Properties, Method etc?

Constructor gets executed only once and it's when you instantiate your class in other classes or methods or even in your service.
ex.
mySampleClass msc = new mySampleClass();
Properties and Methods inside the class won't be affected "unless" you do something like msc.PropertyName="somethingelse"; or msc.MethodName();.

Related

Why can't we access static method through the object in .net

with the following code:
public class test
{
public static void DoSomething()
{
Console.WriteLine("test");
}
}
public class test2
{
public test2()
{
var a = new test();
a.DoSomething(); // invalid
test.DoSomething(); // is valid
}
}
I need to access the static method through the base class, and not through the instance.
But, what would have been the downside of letting the user access it through the instance? It seems to me that it would help with readability.
You can't call a static method from a class instance, because all static fields and methods are associated with the type rather than an instance of said type.
For a deeper understanding of static classes I suggest you read this.
I guess what you are asking is
When calling a static method, why we must specify the class that
defines the method and when calling an instance method, why we must
specify an instance that refers to the object of that class.
To answer this, we must understand how CLR manages things in the background.
Lets try to understand what happens when a new instance is created:
When we “new” up a class’ instance, the CLR creates an object in the managed heap, this object on the heap (among other things) also contains the bytes necessary to hold all of the instance data fields defined by that class as well as any instance fields defined by any base class (say Object class).
This means the instance fields are tied up with that instance of the class that we just created by newing up in our code.
Now, when calling a static method, the JIT compiler locates the class object that corresponds to the type that defines the static method. Note that it doesn’t uses the instance (object) here. Then, the JIT compiler locates the entry in the class object’s method table that refers to the method being called, JITs the method (if first time called), and calls the JITted code.
Notice the difference in how CLR does the discovery of an instance and static methods.
As for every question on a language-decision you allways have to consider the use and the potential harm that is caused by your request. While it may increase your (personal) readability in a very specific case, it adds lots of confusion to readers of your code that don´t have your source-code. Furthermore it would assume a compiler is able to determine if or if not a member actually does something on the instance or not. So the compiler would have far more complicated logic in order to achieve something you can easily indicate yourself by the static keyword.
In fact an instance-method does something with an instance, it does not neccessarily modifiy its state, it can also just use that state and process some operation. Making something available on that instance-level which does not have instance-semantics seems quite counter-intuituve and breaks the principle of least astonishment - at least for me. If there is a member called on an instance it is supposed to do something with that instance. If or if not this is actually the case is an implementation-detail which a client shouldn´t bother for at all.
Alternatively you can create the static method as an extension method on the base class or the child class. And then you can call it directly from the object instance as you attempted.
Using instance.DoSomething(); would indicate your are calling a method of the instance (which of course would not be true since it is a static class member, not related to the instance iteself). Because of this, it would probably only lead to confusion.
By using MyClass.DoSomething(); it is easily understood that it is in fact a member of the class (not of an instance) you are calling. Perhaps it will be clearer if you follow standard naming conventions (class name with leading capital).
For further understanding of static members, see the Microsoft docs.
I think this is the key line in the documentation:
Only one copy of a static member exists, regardless of how many
instances of the class are created.
Only allowing access through the Class makes sense in light of the above.

Is there a way to hide/show certain methods when instantiating an object?

This question came to mind while I was writing a class that iterates over a list, with methods next() and previous() that will continuously loop (e.g. if at the last object, return it, and then reset index to 0)
In the constructor I was pondering adding a boolean variable, which if true would just act like a regular iterator with only next() methods and no looping. In this case, having the method previous() would make no sense. So I'm curious, is it possible to hide the previous() method in this case. Is it possible to achieve this somehow in Java or C#?.
What about other languages?
C#
It is possible by making the two methods part of two different interfaces, and casting the object to one of the two interfaces. For example:
interface ILoopingIterator
{
void Next();
void Previous();
}
interface INonLoopingIterator
{
void Next();
}
class PlaysItBothWays : ILoopingIterator, INonLoopingIterator
{
void ILoopingIterator.Next()
{
this.NextCore();
}
void ILoopingIterator.Previous()
{
// since this code will never be shared anyway, put it here
}
void INonLoopingIterator.Next()
{
this.NextCore();
}
private void NextCore()
{
// do stuff here; this method only exists so that code can be shared
}
}
Note that I have made the class implement both interfaces explicitly; this way, users of instances are forced to select which "mode" they want to use the class in. You could implement only one interface explicitly instead (providing a "default" mode that can be changed).
and now:
var looping = (ILoopingIterator) new PlaysItBothWays(); // selects mode A
var nonLooping = (INonLoopingIterator) new PlaysItBothWays(); // selects mode B
Of course this does not stop anyone from casting the instance to the "other" interface if they want to, but if the programmer wants to subvert their own code they can also use reflection which allows much more than that.
Java
In Java, the above is not possible. You can come close by having the class expose methods that return instances of one of the two interfaces, and using the returned value. Of course then the object is really a factory and not a service provider, so that's feels like cheating on the problem.
class PlaysItBothWays
{
public ILoopingIterator asLooping() { return /* something */ }
public INonLoopingIterator asNonLooping() { return /* something else */ }
}
Rather than passing a boolean to a constructor, you should simply use inheritance.
Suppose you have a base iterator that supports only next(). If that's the only functionality you need, instantiate it.
To provide more functionality, inherit from this base iterator, make a class called TwoWayIterator or something like that, and provide a previous() method.
Both of these classes will share a common super class, so you can treat them as one, and you can hide the previous() method by treating an instance as its base class.
It is not possible to hide a method like that in a statically typed language. The best you can do is implement the method to throw an exception (or equivalent) if the method is called.
There are tricks that you can do to make it appear like the methods are not there. For instance, having the class implement two interfaces, and using different factory methods to create them. However, they don't work if the constructor is used directly, or if you want the choice to be determined by the value of a constructor or factory method parameter.
Not in Java. You can't "Hide" methods at runtime. I'd suggest you to create Two interfaces
, one with the next method and the other one extending the first one and adding the "previous" method. Then, you can have 2 factories methods to create an instance of one of these classes.
Please take a look to the Java "Iterator" class
interface Iterator<T> {
T next();
}
interface LoopingIterator<T> extends Iterator<T>{
T previous();
}
Then you can cast them. Similar to the previous C# answer
You can't hide class members at run time (well, not in C# anyway - not sure about Java). If you so worried about Previous() method being used in the context where it is not doing anything useful, then simply have it throw InvalidOperationException in that case.
It is also worth noting that .NET already has standard "iterator" interface. It is called IEnumerable (and generic version IEnumerable<T>) and is forward-only.

How does this "Programming to Interfaces" thing work?

I like the idea of "programming to interfaces" and avoiding the use of the "new" keyword.
However, what do I do when I have two classes that have the same interface but are fundamentally different to set up. Without going into detail about my specific code, I have an interface with a method, "DoStuff". Two classes implement this interface. One is very simple and requires no initialisation to speak of. The other has five different variables that need to be set up. When combined, they allow for literally millions of ways for the class to work when DoStuff is called.
So when do I "new" these classes? I though about using factories but I don't think they are suitable in this case because of the vast difference in setup. (BTW: there are actually about ten different classes using the interface, each allowing the formation of part of a complex pipeline and each with different configuration requirements).
I think you may be misunderstanding the concept of programming to interfaces. You always have to use the new keyword in object oriented languages to create new instances of objects. Just because you program to interfaces doesn't remove that requirement.
Programming to an interface simply means that all your concrete classes have their behavior defined in an interface instead of in the concrete class itself. So when you define the type of a variable, you define it to be the interface instead of a concrete type.
In your case, just implement DoStuff in your concrete classes as each class needs it implemented (whether doing it simply or with 10 other initialized objects and setup). For example, if you have an interface IInterface and class SomeClass which implements IInterface. You might declare an instance of SomeClass as such:
IInterface myInstance = new SomeClass();
This allows you to pass this instance around to other functions without having to have those functions worry about the implementation details of that instance's class.
Well you really have 3 options. Use new, use a factory or use an DI container. With a DI container your five variables would most likely need to be in a configuration file of some sorts.
But to be completely honest it sounds like you're making your life harder than it needs to be by forcing yourself into a corner. Instead of coding to some ideal, rather code in a manner which best facilitates solving the problem at hand. Not saying you should do a hack job of it, but really, saying you don't want to use new, that is really making your life harder than it needs to be...
Regardless of what you use, at some point you're going to have to construct instances of your classes in order to use them, there's no way around that.
How to go about doing that depends on what you want to accomplish, and the semantics of those classes.
Take the class you mention with those fields.
Can those fields be read from somewhere? A configuration file, as an example? If so, perhaps all you need is just a default constructor that initializes those fields from such a configuration file.
However, if the content of those fields really needs to be passed in from the outside world, there's no way around that.
Perhaps you should look at a IoC container and Dependency Injection?
If you are passing that many configuration parameters into your class it may have too many responsibilities. You should look into breaking it up into smaller classes that only have a single responsibility.
Avoiding the new keyword can be valuable because it creates a dependancy on the implementing class. A better solution would be to use Dependancy Injection.
for example
public interface IDoStuff
{
void DoStuff();
}
public class DoStuffService
{
private IDoStuff doer;
public DoStuffService()
{
//Class is now dependant on DoLotsOfStuff
doer = new DoLotsOfStuff(1,true, "config string");
}
}
public class DoStuffBetterService
{
private IDoStuff doer;
//inject dependancy - no longer dependant on DoLotsOfStuff
public DoStuffBetterService(IDoStuff doer)
{
this.doer = doer;
}
}
Obviously you still have to create the IDoStuff object being passed in somewhere.
An Inversion of Control (IoC) container is a good tool to help with implementing this.
Here is a good tutorial for Castle Windsor Container if you are interested in learning more. (There are many other IoC containers, I just happen to use this one.)
The example in your question was very abstract, so I hope this answer is helpful.
If I understand you correctly the problem is with different initialization. You need to provide for two classes that have the same interface. One does not need anything, and the other needs some paramaters and calls some complex initialization.
You should use have a constructor that gets InitializationParameter. Both classes should get it. One with a simple interface that does not need to get anything from it. The other that needs params and will get them from it.
If you are concerned about initialization you can use factory, just ask it for some interface providing this init parameter and factory will create, init and return to you the object according to the values you provided.
If something is not clear - please ask.

Possible to use a singleton with a non-default constructor in C#?

I'm implementing a notification framework for one of my projects. As i want it to be very generic, the user can use several transport layers, so that he doesn't really need to care about using one delivery method (lets say WCF) or another (for eg ActiveMQ).
The interface the user has access is of course independent of the delivery method (WCF or ActiveMQ).
Still, the two classes (consumer and producer) implements singletons, so they actually use default constructors (meaning, no parameters).
My problem is that i would like to have one parameter, the delivery method the user want to use.
But as far as i know, singleton only use default constructors? which is normal, as there should be no point of using singletons with parameters.
So, what are my options here? not to create a singleton? create a method to set the delivery method?
Thank you very much for your help,
Sebastian
You can certainly have parameters with singletons, except instead of passing the parameter into a constructor, you are passing it into the getInstance() method. Your overridden constructor needs to be private of course for a true singleton implementation. My example is written in Java but applies for C# as well.
Example:
Singleton s = Singleton.getInstance(42);
In the Singleton code:
private Singleton() {
}
private Singleton(int num) {
//set num
}
public getInstance(int num) {
//singleton code (calls the private non-default constructor if an object
//does not already exist)
}
There are some dependency injection frameworks like Spring.Net which might help you. You can effectively pass a parameter in a configuration file for your singletons constructor.
Link to a Spring Framework example
Might I suggest that if you have two different behaviours required of your singleton that you might want to subclass. That way you get the behaviour that you want by calling the singleton of the class behaviour you want.
You can do this easily with a dependency injection framework. I have a similar construct in my current project using MEF. All that's required is to use the constructor injection options, and add that assembly and the requested dependency's assembly to the catalog, and it wires it up correctly.
Another option is to have some form of initialize function that takes your option, and constructs the singleton instance. Instead of constructing it on first access, you can construct it during the initialization call. The downside here is that you need to make sure to initialize your singleton before you use it (typically at program start, using a config file).
A similar, but less error-prone option, is to just have the singleton lazy initialize, and give it a "default" option. Allow the caller to set a static property to alter which option is constructed, so if it's set prior to the singleton's construction, you'll get a different default. This can be confusing, though, since again, you need to make sure you set the property before accessing the singleton, or you'll get unexpected behavior.
I know it is late to answer the original question, but i just had this problem and here is how i solved it. Might not be ideal, but it seems to work.
I created a Init method that must be called before trying to use the singleton instance.
public void Init(/*parameters*/)
{
if (_isInitialized)
{
throw new InvalidOperationException("Component is already initialized!");
}
//do your work here
}
Any other access to the singleton instance (properties get, set, method calls) will throw an invalid operation exception telling that the object was not initialized.
I think this does what i need, is less confusing than GetInstance(params) because there is no risk of misunderstanding what the method does. The downside is it will not throw compilation time errors, but the first run without the initialization done will throw an exception, so it should be good enough.

What is the best way to ensure that all necessary class properties are set before returning an object which will be used somewhere else

I have a class that requires a specific method to be called before being used by other objects, this method implements all the required logic and sets the properties of the class to their respective values. How can I ensure that the method of this class is called before the object is returned for use by other objects? I heard that it is a bad idea to implement logic in the constructor so I cannot call this method in the constructor. A code example for this sort of implementation is as follows:
SomeClass myClass = new SomeClass("someName");
//Class must call this method if object is to be of any use
myClass.ConvertNameToFunnyCharacters();
return myClass;
If it's essential that the object is constructed correctly then it's not a bad idea to put the logic in the constructor. You should consider putting the logic in another method - which should be public if you want to be able to "reset" the object back to its default state.
If that method needs to be called before the class can be used then it sounds to me much like what a constructor should be doing. And a constructor is also just a special method, so what should be wrong about "implementing logic in the constructor"?
Make your constructor internal, protected or private according to your needs and implement a Factory pattern.
This is how to proceed when you need some object initialization to avoid high object dependencies.
http://msdn.microsoft.com/en-us/library/ms954600.aspx
Putting a lot of logic in the constructor can lead to a few problems:
If the constructor calls methods of the object, those methods run in a partially constructed object. This can really bite you when you override the method in subclasses: in Java and C# the subclass' implementation will run before the subclass' constructor has initialised the extended state of the object and so fail with null pointer exceptions. C++ works more "correctly" but can cause different confusing effects.
It makes unit testing with mock objects a bit more complicated if the constructor calls back out to objects passes as parameters.
So, I prefer to keep constructors as simple as possible: just assign parameters to instance variables. If I need to perform more complex logic to initialise an object I write a static factory function that calculates the constructor parameter values and passes them to a simple constructor.
The reason it isn't recommended to have a lot of logic in the c'tor is that while in the c'tor the object still isn't valid. If that's what your "other" method does, then it's fine as part of the c'tor.
According to me I will call it in the constructor or you'll make a burden on the class user to call this method before using it

Categories

Resources