Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are structs within classes passed as value?

Tags:

c#

.net

I have:

A struct

struct Data { int a; int b; }

A class containing the struct

class Packet {
    Data DataStruct;
}

When I now instantiate my class, I assume that the struct lives on the heap. If I now do something like

SomeClass.Process(new Packet().DataStruct);
SomeClass.Process(new Packet().DataStruct.a);

will it be passed as value?

If not, is there any reason not to make the struct into a class instead?

like image 313
lejon Avatar asked Feb 16 '11 10:02

lejon


People also ask

Can a struct inherit from a class?

Summary: Yes, a struct can inherit from a class. The difference between the class and struct keywords is just a change in the default private/public specifiers.

Do structs need to be passed by reference?

A struct can be either passed/returned by value or passed/returned by reference (via a pointer) in C. The general consensus seems to be that the former can be applied to small structs without penalty in most cases.

How are structs passed?

Structs can be passed as parameters by reference or by value.

Can a struct be inside a class?

Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.


2 Answers

structs are value types, so it will be passed as value. Classes are reference types.

Everything will be passed as value unless out or ref is specified.

like image 154
Neil Knight Avatar answered Sep 28 '22 02:09

Neil Knight


A struct is always passed by value. In other words, a copy of it is created and provided to the called function.

While the struct is allocated on the heap, its actually part of the class its contained by rather than as a separate entity.

like image 29
Nick Avatar answered Sep 28 '22 01:09

Nick