Structure Declaration (class level or proc level)

  • Thread starter Thread starter Cybertof
  • Start date Start date
C

Cybertof

Hello,

I would like to understand the difference between declaring a
structure/variable in a class body, and doing the same thing in a
procedure body.

Example :
In the following code, what are the differences between mCustomer1 &
mCustomer2 ?


class MyClass
{
struct CustomerStruct
{
public string sName;
public string sPhone;
}
CustomerStruct mCustomer1;

public void Test()
{
CustomerStruct mCustomer2;

mCustomer1.sName="John";
mCustomer2.sName="Arnold";
mCustomer1.sPhone="111";
mCustomer2.sPhone="222";

// What are the differences between the 2 structure
// variables ?
}
}



Regards,
Cybertof.
 
Cybertof said:
Hello,

I would like to understand the difference between declaring a
structure/variable in a class body, and doing the same thing in a
procedure body.

Example :
In the following code, what are the differences between mCustomer1 &
mCustomer2 ?


class MyClass
{
struct CustomerStruct
{
public string sName;
public string sPhone;
}
CustomerStruct mCustomer1;

public void Test()
{
CustomerStruct mCustomer2;

mCustomer1.sName="John";
mCustomer2.sName="Arnold";
mCustomer1.sPhone="111";
mCustomer2.sPhone="222";

// What are the differences between the 2 structure
// variables ?
}
}

mCustomer1 will exist if an instance of MyClass exists.
mCustomer2 will exist only if the Test function is called, and will be
destroyed when Test() ends
The changes done on mCustomer2 are unusefull as they will be 'forgotten'
when the Test function ends (mCustomer2 wont exist anymore)
 
Cybertof said:
I would like to understand the difference between declaring a
structure/variable in a class body, and doing the same thing in a
procedure body.

You can't declare a class or structure within a method - only in a
namespace or in a class directly. However, the differences with
variables are:

o Local variables (those declared in a method) are only "valid" for the
lifetime of that method. After that, they "go away" - there's no
way of getting the value back. Also, there's one set of variables
for every method call - if you call it recursively, you get that
many sets of variables, rather than them all being the same.

o Instance variables (declared in a class or struct, but not static):
there's one set of these for each instance, and they survive for
the lifetime of the instance.

o Static variables (declared in a class or struct, with the static
modifier): there's one set of these for the whole type, which means
(in most cases, ie where you're not using multiple AppDomains etc)
you have one set for the lifetime of the app. They're not tied
to any particular instance.
 
Back
Top