How to create an instance of an object in c# - c#

Greeting for the day!
I have a question in my mind and looking for answer from some days.
If my understanding is correct then only diff between Instance and object is :-
instance means just creating a reference(copy) .
object :means when memory location is associated with the object( is a runtime entity of the class) by using the new operator
Now i want to know how to create an instance of an object.
Please give explanation with sample code
Any help will be appreciated.
Thanks

By your explanation it's not called an instance, but a reference of an object. An instance of a class is called an object. I think your question is: "What is the difference of an object and a reference variable?" I'll try to explain it with some examples:
Foo f;
I just declared a reference variable. This is not an object but only a reference that refers to an object.
f = new Foo();
Now I created a new object and assigned it to the f reference variable so every time I do something to f I refer to the Foo object. Like when I call f.Name = "MyFoo"; I refer to the foo object.
Foo otherFoo;
Now I declare another reference variable.
otherFoo = f;
What we have here now is having ONE object in the memory but TWO reference variables refering to the same object.
f.IsFoo = true;
bool isotherFooFoo = otherFoo.IsFoo;
This last line will return true because we changed the IsFoo property to true and f and otherFoo reffer to the same object.
I hope that explains you everything. :)

You don't create "an instance of an object", you create an instance of a class (or struct). An object is an instance of a class.
If you do:
Foo f = new Foo();
You create an instance of the Foo class.

In the phrase "an object is an instance of a class", the word "instance" does not really have a technical meaning that is different to the word "object", it is just a way of defining, in English, what the word "object" means. The meaning of "instance" is really meant to be the same as the meaning of "object". We can break this down as follows:
an object is an instance of a class
an object = instance of a class
an object = instance

In C# 9.0 there is a new way to initialize a class by Target-typed new expressions.
You can initialize the class like this:
Foo f = new();
Note, f is a reference to the class Foo.

We have a class ABC
Class ABC
{
string name="";
public ABC()
{
this.name = "A1";
}
public ABC(name)
{
this.name = name;
}
}
An Instance of a class can be created as:
ABC a1 = new ABC();
or
ABC a1 = new ABC("James");

You create instance of a class and not the object.

Related

C# Get class declaration name

Is it possible to get the declaration name of a class (dynamically) and pass it as a parameter in the constructor to set the name variable in the class itself?
Example:
public class Foo
{
public string name;
public Foo()
{
name = GetClassName();
}
}
public class SomeOtherClass
{
Foo className = new Foo();
Console.WriteLine(foo.name);
}
As result I would expect it to write: "className".
No. That is not possible. There is no way to pass in a variable name without using a parameter.
This is the closest you can get:
Foo className = new Foo(nameof(className));
That sounds like a weird requirement. A variable is nothing but a reference to an object. The name of that reference has by no means anything to do with what this variable reference. Thus the actual referenced object doesn´t know anything about its references. In fact you may have even multiple references to the same Foo-instance. So how should the instance know to which variable you refer to? So what should happen in the following example:
var f = new Foo();
var b = f;
Now you have two references to the same instance of Foo. The instance can´t know which of hose is the right, unless you provide that information to it by using a parameter (e.g. to your constructor). The thing gets even worse if you have a factory creating your Foo-instance:
void CreateFoo()
{
return new Foo();
}
// ...
var f = CreateFoo();
Now you have a further indirection, the constructor of Foo can surely not bubble though all layers in your call-stack until it reaches some assignement where it may get the actual name. In fact it´s possible that you don´t even assign your instance to anything - although this is merely a good idea:
CreateFoo(); // create an instance and throw it away
Anyway if you want to set a member of an instance to some value, you should provide that value to the instance. The answer by Patrick shows you how to do so.

What happens with uninitialized fields?

I've read these SO questions:
what-happens-with-unused-class-properties
do-unassigned-properties-take-up-memory-in-a-class
does-declaration-in-c-sharp-allocate-memory-or-is-it-the-new-operator-that-alloc
memory-allocation-of-class-objects
I'm very sorry, that I ask this question. But its still not clear.
Until now, I understood, uninitialized fields like this:
private MyClass Object;
Are getting their default value. And I learned that the default value of an object is null.
But I don't know if it's like this:
private MyClass Object = null;
//or like
private MyClass Object = new Class() { MemberOne = null, MemberTwo = null };
Or is it completely something other?
Unused field consumes memory for each instance of a class. They are simply initialized automatically to their default values.
How Jeff Bridgman wrote it is
private MyClass Object;
//Is equal
private MyClass Object = null;
You can test it by yourself in this dotnetfiddle.

passing objects as parameters

The application is printing 24 but shouldn't it be printing 18 when we know that without ref keyword only a copy of object is passed and no change is made to the original object.
I have created a class called myclass and an object me. age is a public variable in class myclass.
I have set me.age as 18 and through the method show I have changed it to 24.
class Program
{
static void Main(string[] args)
{
myclass me = new myclass();
me.age = 18;
show(me);
Console.WriteLine(me.age);
Console.ReadLine();
}
public static void show( myclass you)
{
you.age = 24;
}
}
class myclass
{
public int age;
}
Don't confuse the variable and what the variable points to.
When you have:
MyClass myVar = new MyClass();
MyClass myVar2 = myVar;
That will create only a single instance of an object, but 2 variables pointing to it.
The same thing is happening to your parameter: you is a copy of the variable me, but both point to the same object. So when you modify you.age, you are also modifying me.age.
In your function, if you then did
you = new myClass();
only then would me and you refer to different objects. If you did this, me would still point to the original object.
If you added ref to the parameter you, then if you did
you = new myClass();
then the variable me would be updated to point to that same object.
For objects, you need to separate the variable from what the variable points to.
It's printing the right thing.
myclass is an object, and the default behavior is to pass the reference of the object in C#, so when you don't specify anything, you pass the reference.
If you declare struct myclass though, you'll have the behavior you want, because structs aren't references by default.
You're probably confusing this with C++ classes. In C#, classes are reference types, which means that whenever you have a variable of a type that's class, that variable doesn't hold the object itself, it holds only a reference to it (you can think of it as a pointer). So, when you pass your object into a method, you actually pass a reference to that object. This means the behavior you're observing is correct.
C# also supports value types (unlike e.g. Java), which you create by using struct instead of class. If you changed myclass into a srtuct, you would get the behavior you expected.
You are confusing value types and reference types.
public void addTwo(int a)
{
a += 2;
}
...
int a = 5;
addTwo(a);
Console.WriteLine(a); // will give "5";
public void addTwo(ref int a)
{
a += 2;
}
...
int a = 5;
addTwo(ref a);
Console.WriteLine(a); // will give "7";
For reference types (anything that is defined as class instead of struct, what you are passing on is a reference to the object, not a copy. So you are in fact changing the object.
You are sending an object to your function.
Not an atomic type or a struct, therefor it is sent by reference (this is how C# works), anything you change in this object in the function will also change in the original object because it is the same.
More information about passing parameters: http://msdn.microsoft.com/en-us/library/0f66670z(v=vs.71).aspx

Object passed by reference and not by value

I'm writting a piece of code (c#) in windows phone 8 (had the same issue with windows 8).
And I am wondering, how to passe value of one object and not his reference.
Let me explain with one exemple :
public MyClass
{
private Foo foo //my object.
public void Init()
{
foo = new Foo();
foo.age = 5;
ChangeFooValue(foo);
}
private void ChangeFooValue(Foo temp)
{
temp.age = 10;
//I want to change temp and NOT foo.
//But at the end of this
//foo.age = 10;
//and
//temp.age = 10;
}
}
Solved :
I had this in my class to create a deep copy :
public Foo DeepCopy()
{
Foo other = (Foo) this.MemberwiseClone();
return other;
}
ps: It's maybe a dumb question (if it is, please, provide me some tutorial to be able to resolve it by my self).
Reference type's address is passed by value, that is why you are seeing this effect. You may create a deep copy of your object before passing to the function.
You should see: Parameter passing in C# by Jon Skeet
I prefer the other answer but there is another approach you could use to dupe the object, using an overloaded constructor. It is described here:
http://www.codeproject.com/Articles/14686/C-Parameter-Pass-object-by-value-The-copy-construc
From there you could pass like so
ChangeFooValue( new Foo(foo) );

How do you access data in another class in C#?

I need to share data between classes in C#. Sounds easy enough. I have a collection that is loaded with data in a class. Let's say it is defined like this:
public class AppAdmin: IApplicationThingy
{
public ObservableCollection<Data> DataCollection;
Now, in another class, I want to look at DataCollection. Both classes are in the same namespace. AppAdmin.DataCollection does not work. Can you help?
You have to have an instance of AppAdmin to access DataCollection
var appAdmin = new AppAdmin();
var data = addAdmin.DataCollection;
or if the design permits, you can make DataCollection static
public class AppAdmin: IApplicationThingy
{
public static ObservableCollection<Data> DataCollection;
and then you can access DataCollection as you mention in the question by
var data = AppAdmin.DataCollection;
By the looks of it, you are trying to access an instance member like a static member. Static members are attached to the class/type and and instance member is attached to an object. If you are looking to access the "DataCollection" as you have it above, you will need to create an AppAdmin object first and then you should be able to access it.
Try this.
var aAdmin = new AppAdmin();
var collection = aAdmin.DataCollection;
AppAdmin.DataCollection is an instance member of AppAdmin. This means that you need an instance of AppAdmin to access AppAdmin.DataCollection for a particular instance.
Thus, at some point you need a reference (be it through a variable of type AppAdmin or an expression that evaluates to an instance of AppAdmin) to be able to access AppAdmin.DataCollection for a particular instance.
So, somehow, someway, you need
AppAdmin appAdmin = // expression that evaluates to an instance of AppAdmin
var dataCollection = appAdmin.DataCollection;
or
var dataCollection =
(expression that evaluates to an instance of AppAdmin).DataCollection
to get a reference to AppAdmin.DataCollection for a particular instance of AppAdmin.
Let's put it more simply:
class Dog {
public IEnumerable<DogLeg> Legs { get; set; }
}
A Dog has Legs. To be able to get a particular Dog's Legs, you need an instance of Dog to receive the request for its Legs.
Similarly, an AppAdmin has a DataCollection. You need a particular instance of AppAdmin to receive the request for its DataCollection.
So, to access an instance member (be it a field, property or method) you need an instance object to receive the request.
You have to instantiate the object and then call the data filed.
AppAdmin aa = new AppAdmin();
aa.DataCollection;
You need to have an instance of the class in order to access its members.
In order to share the data in the instance, you need to pass it around:
// in one object that needs the object
var myAppAdmin = new AppAdmin():
var myData = myAppAdmin.DataCollection;
// call to another object, passing in the class
myOtherClass.GetDataFromAppAdmin(myAppAdmin);
Maybe you want to make it static?
public class AppAdmin: IApplicationThingy
{
static public ObservableCollection<Data> DataCollection;
Depends...
If the data just needs to always be available outside of any given instance of the object, just make it static:
public static ObservableCollection<Data> DataCollection;
If the data is tied to an instance of the object, then you access it from the instance and not from the class:
var myObj = new AppAdmin();
myObj.DataCollection ...
But keep in mind the difference between static and instance values. It's an important subject to learn. Trying to mix the two often leads to strange bugs.

Categories

Resources