C
C#11mo ago
yz

C++ struct initializing in C#

in C++, we can do this -
struct Foo
{
int A;
int B;
};
Foo a = { 5, 7 };
std::cout << a.A; // 5
std::cout << a.B; // 7
struct Foo
{
int A;
int B;
};
Foo a = { 5, 7 };
std::cout << a.A; // 5
std::cout << a.B; // 7
But I found that I can't do this in C#. Do I have to assign values by each one like this?
a.A = 5;
a.B = 7;
a.A = 5;
a.B = 7;
I want to know how to assign member values simply in C#.
7 Replies
TheRanger
TheRanger11mo ago
Foo a = new Foo{ A = 5, B = 7 }; however you can do Foo a = (5, 7); if you defined an implicit operator that has a parameter of a specific ValueTuple
yz
yzOP11mo ago
So I have to make an operator if I don't want new?
MODiX
MODiX11mo ago
TheRanger
REPL Result: Success
struct Foo
{
public int A;
public int B;

public static implicit operator Foo((int a, int b) v)
{
return new Foo{ A = v.a, B = v.b };
}
};

Foo a = (5,7);
Console.WriteLine($"{a.A} {a.B}");
struct Foo
{
public int A;
public int B;

public static implicit operator Foo((int a, int b) v)
{
return new Foo{ A = v.a, B = v.b };
}
};

Foo a = (5,7);
Console.WriteLine($"{a.A} {a.B}");
Console Output
5 7
5 7
Compile: 530.825ms | Execution: 42.423ms | React with ❌ to remove this embed.
TheRanger
TheRanger11mo ago
yes C# probably didnt allow this syntax Foo a = { 5, 7 }; due to safety reasons
yz
yzOP11mo ago
I see Thanks!
sibber
sibber11mo ago
Foo a = new() { A = 5, B = 7 };
Foo a = new() { A = 5, B = 7 };
is also valid
Jester
Jester11mo ago
i think new struct means that it gets allocated on the heap in c++? in c# thats not always the case. it allocates on the stack in your method but ofc if you assign it to a field in a class which is on the heap then its on the heap but thats the same as in c++
Want results from more Discord servers?
Add your server