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.
Related
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 2 months ago.
Improve this question
In this code
using System;
namespace Hello
{
class TestEmployee
{
static void Main()
{
Employee employee = new Employee();
employee.salary = 1000;
employee.bonus = 100;
employee.CacalculateTotalPay();
Console.ReadKey();
}
}
class Employee
{
public double salary;
public double bonus;
public void CacalculateTotalPay()
{
Console.WriteLine(salary + bonus);
}
}
}
Why should we make a instance of a class with the new keyword when we already declared the employee variables type with Employee class?
I didn't tried anything.
When you declare a variable for a class without the new operator any assignment, like this:
Employee employee;
you don't actually have an instance of the class yet. There is no Employee object here. What you have is a variable with the potential to refer to a class instance. Initially there isn't anything there; only the potential... it is a null reference. Therefore we might also create a new instance of the type and assign that new instance to our variable:
Employee employee = new Employee();
You could avoid this by making the Employee type static. Then, instead of declaring a variable at all you would refer to its members via the type name (ie Employee.salary). However, that's limiting. If you refer to the members via type name you would have no way to distinguish one employee from another, and you likely expect to have many more than just the one employee.
Therefore we do not use static and instead create new instances so that each instance can represent a different employee.
This can be confusing for new programmers, because the first exposure to code is often via a class with a static Main() method, where you did not need to create an instance, and with primitive types like int and string that have support in the language so you don't need to use the new operator. It may be some time before you progress far enough to need to worry about object instances. But rest assured, over time instances are the norm, and static and struct will be less common.
Finally, it is important to come to terms with the difference between object instances, references, variables, and types (classes/structs). Those are four different kinds of thing, and it is difficult to write effective code without understanding how they relate to each other.
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 8 years ago.
Improve this question
I have a problem with changing a variable from different class. Even tho I used access modifiers (get and set), compiler still sees it as read only, and I cannot change it within another class.
private float speed;
public float Speed
{
get {return speed;}
set {speed = value;}
}
I'm not sure if this matters, but this variable is from my main, abstract class and I use it in other classes. What is happening here, is that I assigned value to this variable in one class (Player.cs) and I'm trying to change it in another class by initializing its object (Physics.cs). They are both inheriting from that main, abstract class.
If you're only setting speed once, just use a readonly variable and set it in the constructor:
public class Physics
{
private readonly float speed;
public Physics()
{
this.speed = 5;
}
}
You can set a readonly variable exactly once.
If you really do need to change speed within the lifetime of your object, just use an auto property anyways for simplicity:
public float Speed {get; set;}
If you're trying to access speed from a child class, make sure that its defined as protected (not private) in the base class. private really is private. Nothing outside of the class where it is defined can access it. Protected allows classes that inherit to access it.
(If I understood your question correctly, that is. I'm confused, though... if you are trying to access the speed variable directly, then why have the public properties?)
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 8 years ago.
Improve this question
I want to know the relation between instances of parent child in c#.
Suppose you have two classes Base and Derived:
Base b = new Base()
Derived d = new Derived()
Derived db = new Base()
Base bd = new Derived()
then what is the meaning of above types of objects
Please suggest I am confused.
Assuming that Base is actually the base class of Derived....
Line 1 contains an instance of the base class.
Line 2 contains a instance of the Derived class.
These are both "standard" variables, where the variable type exactly matches the instance it contains.
Line 4 is an instance of derived class, but restricted to only accessing base class methods. Think of it as a slightly restricted view of the derived class.
Line 3 should produce a compilation error. You can't place an instance of a base class in to a variable of a more restrictive type. Think of it like this "All Dogs(derived class) are Animals(base class), but not all Animals are Dogs.
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 nonstatic 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 nonstatic 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
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