making instance of class 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 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.

Related

Using static variables and methods vs. non-static [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 4 years ago.
Improve this question
I am developing an ASP/c# webform where I am using JQuery as well. I came into a scenario where I need to call. C# function from JQuery. In order to that, I found that function in c# has to be a static method (web method).
The problem is that I need to access all variables, arrays, etc which I used to populat some data and these are not stated c variables. Also, from the web method I need to re-use some the functions which are not static. I ended up gradually just changing all methods and variables to static.
I would like to know if the approach I am taking is correct, and whether there is any pitfall of using static variables/methods and what in simple words makes a difference between static/none-static.
Static variables can be called directly by using class names such as
public class IhaveStatic
{
public static string Hello = "Hello I am A";
}
When you use static this means this will be in memory for life time of your process.
now consider another class as
public class IhaveNoStatic
{
public string Hello = "Hello I am B"
}
public class C
{
Console.WriteLine(IhaveStatic.Hello); // Correct
IhaveNoStatic obj = new IhaveNoStatic();
Console.WriteLine(obj); // Correct
Console.WriteLine(IhaveNoStatic.Hello); // Compile time error
}
as you can see that you need to create object of that class "IhaveNoStatic" to access non-static variable. So, this will be in memory until there is an instance of that class exist.
So, basically it's on your requirement but it is good to use less static variable in your programs.

How to initialize field in class C#/.Net in efficient and safe way? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Here is two classes MyClass and Helper, in order to have one instance of Helper class in MyClass it could be initialize with property:
public class MyClass
{
private IHelper _helper;
private IHelper Helper
{
get
{
if (_helper != null)
{
_helper = new Helper();
}
return _helper;
}
}
}
or constructor:
public class MyClass
{
private IHelper Helper { get; set; }
MyClass()
{
Helper = new Helper();
}
}
The question: What is benefits and potential issues with each solution? Is it some other better options?
The two approaches are not identical:
The first approach creates _helper on the first read; if Helper property is never accessed, no instance of Helper is created
The second approach creates _helper eagerly, meaning that you would have an instance of Helper in each instance of MyClass.
The choice between these two behaviors is based on your requirements, not on an opinion. Note that you can use Lazy<T> class to achieve the behavior from your first example with less code:
public class MyClass {
private Lazy<IHelper> _helper = new Lazy<IHelper>(() => new Helper());
private IHelper Helper {
get => _helper.Value;
}
}
Those two examples don't do the same and so there is no "matter of style", but of "how should it work". The difference is minor but still there is one:
In your first example the instance of Helper is only created if it is accessed at least once, but in your second example it is always created even if it is not needed.
Also in the second example it has a private setter an thus can be changed later on in time again.
IMO you should use the first one if it is not always used and the second one if it is needed every time, but then make the property read-only (remove the setter - setting in the constructor still works if your compiler is up to date).
Another shorter version for the first one I tend to use in such cases (Lazy<T> has some minor overhead and do not use it for "singleton like patterns"):
private IHelper helper;
public IHelper Helper => helper ?? (helper = new Helper());
NOTE: This code-example is NOT thread-safe, so if that is a requirement use the example from dasblinkenlight. Here it could happen that two instances of Helper are created if the property is accessed the same time by two threads and the second one is then set to helper in the end. If that is not the case or no problem it is safe to use. If I remember correctly the thread-safety is also the main reason why Lazy<T> creates some measurable overhead which led us to not use it in all cases.

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.

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

Why not allow Extension method definition in nested class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I would find it convenient/logical to write my exensions for a class in a nested class. The main reason is I could simply name that class Extensions and let it's outer naming scope give it a unique type name for the compiler.
What is the technical reason to disallow something like:
public class Foo
{
ObjectSet<Bar> Bars { get; set; }
public static class Extensions
{
public static Bar ByName(this ObjectSet<Bar> bars, string name)
{
return bars.FirstOrDefault(c => c.Name == name);
}
}
}
Whereas now I have to create a separate free standing class.
Update/Note: I wasn't imagining that the fact it was an inner class would affect the scope of availability of the extension method. I only wanted to address the practical coding issue a separate class with a separate name.
The key point here is that nested classes can access private fields in the outer class.
So the following code works:
public class Foo
{
private bool _field;
public static class Extensions
{
public static bool GetField(Foo foo)
{
return foo._field;
}
}
}
Here you are explicitly passing in an instance of the class, and a static method is allowed to access a private field... seems reasonable:
bool fieldValue = Foo.Extensions.GetField(new Foo());
However, although extension methods are just an alternative syntax for static methods, they are invoked the same way as non-static instance methods.
Now if extension methods were allowed in nested classes, they could in fact access private fields, and they would be that much closer to instance methods. This could lead to some unintended consequences.
In summary, if this were allowed:
public class Foo
{
private bool _field;
public static class Extensions
{
public static bool GetField(*this* Foo foo) // not allowed, compile error.
{
return foo._field;
}
}
}
Then you could write the following code, making the extension method behave a bit more like an instance method than it should be:
var foo = new Foo();
var iGotAPrivateField = foo.GetField();
Edit as a result of comments
Why is it a bad idea for extension methods to be equivalent to instance methods?
In Eric Lippert's words (emphasis mine):
So, yes, the oft-heard criticism that "extension methods are not object-oriented" is entirely correct, but also rather irrelevant. Extension methods certainly are not object-oriented. They put the code that manipulates the data far away from the code that declares the data, they cannot break encapsulation and talk to the private state of the objects they appear to be methods on, they do not play well with inheritance, and so on. They're procedural programming in a convenient object-oriented dress.
There is no technical reason for it - just practical. If you have an extension method that is limited in scope to a single class, just define it as a regular static method in your class and remove the 'this'. Extensions are for sharing across several classes.
I guess the idea behind disallowing this thing is because Extension Methods are applied for all entities across the namespace.
If you will create a nested Extension Methods class then it will be applicable only to class where it is nested. In that case its not point creating an extension method. Then any normal non-extension method would do.

Categories

Resources