C++ Template in C#

manala

New member
Joined
Jun 8, 2022
Messages
3
Programming Experience
10+
I have a template in C++ that looks like this:
C#:
template<typename T>
static void initStruct(T* t)
{
     memset(t, 0, sizeof(T));
     t->member1 = [something];
}
Note that T can be different kind of structs and each one has "member1" but the size for each struct can be different.
 
Last edited by a moderator:
Do you have a C# question?

As an aside, C# Generics may look like C++ templates, but they are actually two different creatures and work through completely different mechanisms.
 
Yes, my question is how I can do the code in the initial post in C#. Basically, I need to reset the structure and then set a couple of members in that structure. As mentioned, there can be different structures, i.e. it is not always the same type BUT all of them have the same members that I need to set in initStruct. The only way I can think of for doing the later is having a base class with the same members and then I can set those. But then how would I reset the rest of the members? Also, I have dozens of different structures and currently there is no base class so I would have to rewrite all that code as well.
 
You do know that C# automatically zeroes all it data structures at construction time, right? Also, it's the job of the constructor to initialize the various members if you need to initialize them to something else other than their equivalent to zero values. So there is no real need for you to do that.

As you've figured out, the only way to achieve what you want to do (without using unsafe code and pointers) is to make sure that all the structs or classes that you pass into the method have a common base class that has those common members.

I think you are trying to solve a problem that doesn't exist in the C# language.
 
Back
Top Bottom