need clarification for Constructors in c# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to know whether my understanding on the constructors is correct or not. I just tried to attempt a quiz for constructors but confused whether my understanding is correct or not
--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, the compiler automatically provides a default constructor.)
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.)
--> A static constructor in a non­static class is called once on each object creation. – False (If a static constructor has been called once, compiler will not call it again, it will get called once only .The execution of a static constructor is triggered by the first of the following events to occur within an application domain: 1. An instance of the class type is created. 2. Any of the static members of the class type are referenced.)
-->You can specify on the constructor which classes of interfaces that class is inheriting
( i don't know please clarify )

--> Every class needs at least one constructor defined - False (In C#, if you don't provide one, > > the compiler automatically provides a default constructor.)
- Your understanding is Correct
--> It’s possible to avoid a class being instantiated by simply having only a private constructor on it. – False (A private constructor is a
special instance constructor. It is generally used in classes that
contain static members only. If a class has one or more private
constructors and no public constructors, other classes (except nested
classes) cannot create instances of this class.)
- You can have a private constructor, in which case other classes cannot create instance of it (but why will you do that?)- People do that to put some control in object's instantiation, as what they do commonly in some design patterns. In a nutshell, you can still create an instance of a class with private constructor thru some other means (e.g. from static methods).
--> A static constructor in a non­static class is called once on each object creation. – False (If a static constructor has been called
once, compiler will not call it again, it will get called once only
.The execution of a static constructor is triggered by the first of
the following events to occur within an application domain: 1. An
instance of the class type is created. 2. Any of the static members of
the class type are referenced.)
- Your understanding is Correct
-->You can specify on the constructor which classes of interfaces that class is inheriting ( i don't know please clarify )
- False, You specify in the class declaration itself the interfaces or classes that the class is going to inherit not in the constructor

Related

Static fields - if only one instance created from the class [duplicate]

This question already has answers here:
Static vs non-static class members
(7 answers)
Closed 5 years ago.
I have been having a hard time deciding when I should declare a class filed as static.
I got the idea that a static field is shared among all objects created from a class, unlike a regular non-static field, which is held by each of the objects.
Then if it is known that only one object will be created from a class (because I have seen such cases many times), what is the meaning of a static field?
If the definition of "static" is "shared among all instances," does a static field serve the same role as a regular non-static field, provided there is only one object created from the class?
I got this old project from my boss to study C#, and I see some fields declared as static in a class, but there is only one object created from the class, and I am a bit confused what the point is if it does not have multiple instances.
You should not decide to use static just because there´s only one single instance. As you´ve already mentioned there is an instance.
The question if something should be static depends on if your member depends on an internal state, that is do you need to set some property befpore you can incoporate with this member. So even if there´s just one single instance existing this instance shares a set of members defining its state. Only when your member could omit all those information from that single instance it should be marked static.
However making some member static makes many things - e.g. mocking - quite hard as you create a heavy dependency on your class holding that member

Making interface from class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having some troubles making an interface for my class. I tried with a simple public void and that worked. But i cannot get it to work with the public static voids in the code below. I think it has something to do with the enum as a parameter in the method. But How do i fix this?
This is the class:
And this is my interface:
Interfaces are contracts. They specify the method signatures for all methods within the contract.
In your interface, you have:
void FFT(/*stuff*/)
Yet, in your implementation, you have defined
static void FFT(/*stuff*/)
Now, why can't we use static? From Joel Spoelsky
Because an interface is a "contract" or an agreement between the consumer (caller) and the provider (callee). An interface describes what and how the calle will provide functionality. There is no need for static members provided by a third party. Static members cannot be overridden by a provider so they do not belong in an interface.
Interface is a contract between caller and callee. Static member belong to class not to the object, so its no point of making method static.
To explain why this really doesn't make sense, the reason to make an interface is so you can pass an object of your class as a reference to the interface type, so the consumer doesn't need to know which underlying type the object is. For example, you might pass an IEnumerable<Foo> to a method that doesn't need to know or care if this is an array or a list or a hashset, etc., it just wants a sequence of Foos.
Static methods are not associated with an instance, so there is no object to reference. There isn't the concept in C# of a static interface which could be used to reference a class rather than an object.
If you had other classes that you wanted to use interchangeably, you could get rid of the static and make these singletons.

Order of creation of instances [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have the following classes:
class X
{
int x = 100;
}
class Y:X
{
int y = 100;
}
and the following decompiled code:
class X
{
int32 x;
public void X()
{
this.x = 100;
base.Object();
}
}
class Y:X
{
int32 y;
public void Y()
{
this.y = 100;
base.X();
}
}
so when I create an instance of Y as in new Y(); I thought that first is created an instance of X type and then an instance of type Y because X is the base class and that base class must be created first than its derived class (Y).
However reading the decompiled code this exists before base and how is possible if base should be created before than this?
Maybe does it exist only one object? And we must always call, first, base class constructor only for initializing purpose?
Practically which is the raison to call first base class constructor if we cannot must create first an instance of that type?
Very confused!
Maybe does it exist only one object?
Yes, exactly. A single object is created, which immediately is of the type specified (Y in this case). All fields (across the inheritance hierarchy) are initially set to the default values of their corresponding types. A single object is created, and then initialized using constructors. Starting from the most derived class, the specified constructor is executed:
If there's a constructor initializer of the form this(...), that is executed. Otherwise, field initializers are executed.
The base class constructor is called; remember that if you don't specify a constructor initializer at all, that's equivalent to base()
The body of the constructor is executed
There's no idea of "base being created" or "this being created".
This is described in sections 7.6.10.1 and 10.11 of the C# 5 specification.
The C# programming guide says (in Fields (C# Programming Guide), emphasis mine):
Fields are initialized immediately before the constructor for the object instance is called.
So before anything else is done (even base constructor calls), the field variables are initialized.

When to use 'Static Methods' in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have a bunch (may be 10 to 15 ) methods in my C# code all of which are 'Static'. Obviously, all of them are called with the ClassName. All works well. But, are they any advantages/disadvantages of using them that way? or would I get any performance benefit if I do not use 'Static' for my methods?
Technically there is slight performance benefit when you are using static method, because you don't need to load instance reference to stack when executing method. But that is really minor optimization which you will not notice.
From programming point of view static methods are hard to mock and they introduce strong coupling with implementation in your code. Also you lose benefits of abstraction and polymorphism when use static methods.
You can make static private methods from instance methods which don't use instance data. But public static methods usually give you problems with mocking and dependency injection, so usually I avoid them. One exception is factory methods which used to create instances of class - Loan.CreateLongTermLoan (thus you can't have constructor with custom name in C#, but you want some descriptive name which describes details of created instance) or Loan.Parse.
If you're worrying about the performance benefit of static methods over instance methods then you're micro-optimizing and without doubt prematurely optimizing. You should worry about good class design before you worry about this sort of thing!
If you've got methods that don't operate on the state of an instance then they are good candidates for being static methods. For example, factory methods are an obvious use of static methods.
If you've got methods that operate on the state of the instance then they need to be instance (non-static) methods. For example, a method that changes a member variable could not be static.
FYI : At the IL level all instance methods are called via a CallVirt instruction, even if they are not virtual. This allows the runtime to generate a NullReferenceException if you call a method on a null reference. A static method is called via the Call instruction.
No performance benefit for being static or not.
If you don't need an instance of the class in a method, then it's a candidate for being marked as static.
The problem with static method comes the moment you need a sub-class.
Static methods cannot be overridden in sub-classes, hence your new classes cannot provide new implementations of the methods, making them less useful.
It's a conceptual question. Does the method …
belong to a specific instance? Then it's not static.
belong to the class rather than to a specific instance? Then it's a prime candidate for being static.
Note that static methods can't access instance members (non-static members) of an object.

C# static method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a problem with a example of my book. From what i have read non static methods cant be used without instance a object of the class. So is this ok ?
public partial class TempAgencyForm : Form
{
public TempAgencyForm()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
...
setVisibility(false);
}
private void setVisibility(bool visibilityValue)
{
...
}
}
Yes, it is fine. One non-static method can call another non-static method.
The call:
setVisibility(false);
can also be written:
this.setVisibility(false);
but the this qualifier is redundant.
However, if you had tried to call a non-static method without instance qualification from inside a static member, that would have been a problem (compile-time error).
I assume you are talking about calling setVisibility(false);. Yes it is fine, neither it or the method calling it are static.
This will all happen within an instance of TempAgencyForm
Yes this is okay, because it's called from within another member.
You're correct, since setVisibility() is not static, it always has to be called in the context of some object of the parent class (TempAgencyForm in this example).
However, btnCalculate_Click() is another member of TempAgencyForm, as such you're able to access the current/local object using the this keyword (this.setVisibility()), which is optional if there's no disambiguity.
static or non static doesnt matter here, you are calling a member function declared within the same object. so short answer is "fine"
how you call TempAgencyForm members may be what you are referring to
in this case (as you have defined) instantiations is required
TempAgencyForm taf = new TempAgencyForm()
taf.setVisibility(false);
however if you have your class definition itself as static, i.e.
public static partial class TempAgencyForm
then,
TempAgencyForm.setVisibility(false);
is suffice (without instantiating the object) as the object is already loaded on stack at the time of application start

Categories

Resources