How do I take an Object and convert it into a struct and vice visa?
public void myMethod1(object myInputObject, out string myOutputString)
{
myInputObject = null;
myOutputString = "";
//Convert object into a struct, then do something
}
Define a struct and set fields values inside your method.
I suppose you want something like this: (pseudo code)
class myclass
{
public int a;
public float b;
}
struct somestruct
{
somestruct(int a, float b)
{
this.a = a;
this.b = b;
}
int a;
float b;
}
myclass mc = new myclass();
mc.a = 125;
mc.b = 12.5;
somestruct s = new somestruct(mc.a, mc.b); //all fields of mc are now in struct somestruct
Related
I have the following code:
struct test {
public int a;
public int b;
public test(int a) {
this(a, null);
}
public test(int a, int b) {
this.a = a;
this.b = b;
}
}
Where I would like to have two different constructors for the test struct, one where I only need to pass in a and another where I can pass in both a and b.
This code does not work, as it fails with a few errors:
For the public test(int a) { line:
Field 'test.a' must be fully assigned before control is returned to the caller
Field 'test.b' must be fully assigned before control is returned to the caller
And for the this(a, null); line:
Method name expected.
The 'this' object cannot be used before all of its fields have been assigned
struct test {
public int a;
public int b;
public test(int a) : this(a, 0) { }
public test(int a, int b = 0) {
this.a = a;
this.b = b;
}
}
You can't assign null to int. Also your variable names are ambiguous. You can use an optional parameter to achieve what you're looking for. Or chaining constructors.
Try this
struct Test
{
public readonly int a;
public readonly int b;
public Test(int a) : this()
{
this.a = a;
this.b = 0;
}
public Test(int a, int b) : this()
{
this.a = a;
this.b = b;
}
}
an alternative is to use an optional parameter with one constructor
public Test(int a, int b = 0) : this()
{
this.a = a;
this.b = b;
}
or instead of 0 to use default(int), or just default
public Test(int a) : this()
{
this.a = a;
this.b = default(int);
}
The : this() call is added by Microsoft when the create constructor tool is used so I have added it here. I think it is just to remind the reader of the code that space in the stack is allocated first and then the fields are assigned.
I also added the readonly keyword because mutable structures are evil and to emphasize the requirements the fields need to be all defined before the constructor ends.
Or you can always use one constructor from another constructor
public Test(int a) : this(a, 0)
{ }
struct a
{
int x;
int y;
byte[] z;
}
var b = new a[] {{0, 0, {0, 0, 0}}, {1,1, {1,1,1}}};
I want to initialize an array of a struct each of which contains an array of bytes. I also tried:
var b = new a[] {{0, 0, new byte[] {0, 0, 0}}, {1,1, new byte[] {1,1,1}}};
A constructor will make it more arranged and readable:
struct a
{
int x;
int y;
byte[] z;
public a(int xv, int yv, byte[] zv)
{
x = xv;
y = yv;
z = zv;
}
}
public void Initialize()
{
var b = new a[] {new a(0,0,new byte[] { 0,0,0}),
new a(1,1,new byte[] { 1,1,2})};
}
Another way According to your Comment
1. if you declare the access modifier of the struct fields as public you
will be able to initialize them using object initializer and not
with constructor (constructor is a method).
2. you can use static class and immediately call that object
3. make b global and public (var is only local keyword) in order to call it
from outside (i would use a more descriptive name then b).
full example:
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("y value of index 1 is: {0}", General.b[1].y);
Console.ReadLine();
}
}
public static class General
{
public static a[] b = new a[] { new a() { x = 0, y = 0, z = new byte[] { 0, 0, 0 }},
new a() { x = 1, y = 1, z = new byte[] { 1, 1, 1 }}
};
public struct a
{
public int x;
public int y;
public byte[] z;
}
}
Use a regular constructor with some values, and write the array contents later:
public struct A
{
const int Size = 256;
// mutable structs are evil.
public int x, y;
// At least make the arrays (not the contents) readonly
readonly public byte[] a;
readonly public byte[] b;
public A(int x, int y)
{
this.x = x;
this.y = y;
this.a = new byte[Size];
this.b = new byte[Size];
}
}
class Program
{
static void Main(string[] args)
{
var x = new A(48, 64);
var y = new A(32, 24);
x.a[4] = 1;
y.b[127] = 31;
}
}
Title of my question is quite different from my question. I am sorry for that because i don't know what should be title for this question.
Suppose i have one class let's say "ClassA"
Class ClassA
{
int x=5;
int y=6;
int z=7;
static public int sum(int a,int b)
{
return (a+b);
}
}
now i need some logic by which i can use sum() like following in another class
int c = ClassA.sum(x,y);
int d = ClassA.sum(x,z);
here i don't need to declare "x","y" and "z" variable. It must be a consider a value that is defined in ClassA.
My question can be silly but just help me.
What should i do ????
You can declare x, y, and z as const:
class ClassA
{
public const int x=5;
public const int y=6;
public const int z=7;
static public int sum(int a,int b)
{
return (a+b);
}
}
Then do:
int c = ClassA.sum(ClassA.x,ClassA.y);
You can pass an instance of an object to a static method, it can invoke instance members on that object.
class ClassA
{
int x=5;
int y=6;
int z=7;
static public int sum(ClassA obj)
{
return (obj.x+ obj.y);
}
}
In other class create instance of class ClassA and pass this object to static method
ClassA objA = new ClassA();
int c = ClassA.sum(objA);
Check if the following code fits your requirement.
Create an enum as:
public enum MyEnum
{
x,y,z
}
The classA code will be:
class ClassA
{
static int x = 5;
static int y = 6;
static int z = 7;
static public int sum(MyEnum enum1, MyEnum enum2)
{
int a = 0;
int b = 0;
switch (enum1)
{
case MyEnum.x:
a = x;
break;
case MyEnum.y:
a = y;
break;
case MyEnum.z:
a = z;
break;
default:
break;
}
switch (enum2)
{
case MyEnum.x:
b = x;
break;
case MyEnum.y:
b = y;
break;
case MyEnum.z:
b = z;
break;
default:
break;
}
return (a + b);
}
}
I have set x,y,z as static because your method is static and you cannot access instance members in static method. Or you can replace static with const while declaring variable x,y,z.
Hope this helps.
I'm new in .net and C# and I'm trying to create an instance of MyStruct, without known the Type before.
so my class receive 3 type in the constructor and I need to create an Instance of MyStruct with this type.
I looked on internet and saw the last part but I can't compile this.
namespace IQUnionTag
{
public class IQUnionTag
{
private struct MyStruct<A, B, C>
{
public A value1;
public B value2;
public C value3;
}
private object MyStructure;
private Type a;
private Type b;
private Type c;
public IQUnionTag(Type a, Type b, Type c)
{
this.a = a;
this.b = b;
this.c = c;
int d = 2;
var d1 = typeof (MyStruct<>); // Doesn't compile
Type[] typeArgs = { a, b, c };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Console.WriteLine(o);
}
}
}
I just want something like
Mystructure = new MyStruct<a,b,c> // this doesn't compile too
typeof(MyStruct<>) make error compile like
Erreur Using the generic type 'IQUnionTag.IQUnionTag.MyStruct<A,B,C>' requires 3 type arguments
i certainly missed something, can you help me to create my instance?
It is not clear what is your purpose but you can do:
public class IQUnionTag
{
private struct MyStruct<A, B, C>
{
public A value1;
public B value2;
public C value3;
}
private object MyStructure;
private Type a;
private Type b;
private Type c;
public IQUnionTag(Type a, Type b, Type c)
{
this.a = a;
this.b = b;
this.c = c;
int d = 2;
var d1 = typeof(MyStruct<,,>); // this is the way to get type of MyStruct
Type[] typeArgs = { a, b, c };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Console.WriteLine(o);
}
}
C++
typedef struct someStruct {
int val1, val2;
double val3;
} someStruct;
someStruct a [1000] = { {0, 0, 0.0}, {1, 1, 1.0}, ... };
The only way to initialize such a table in C# I know of is to write something like
class SomeStruct
{
int val1, val2;
double val3;
public SomeStruct (int val1, int val2, double val3)
{
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
}
}
SomeStruct[] a = new SomeStruct [1000]
{
new SomeStruct (0, 0, 0.0),
new SomeStruct (1, 1, 1.0),
...
};
Is there a way to have a be a (reference to) an array of values of type class SomeClass instead to pointers to those?
Edit:
The point is that I want to avoid having to call new for each struct in the array. So what I want is an array containg 1000 structs and not 1000 pointers to (1000) structs. The reason I am asking is that the way C# handles this appears insanely inefficent to me, involving a lot of memory and memory management overhead (over e.g. C++).
I had tried something like
struct SomeStruct {
int a, b;
double c;
}
SomeStruct[] a = new SomeStruct [1000] { {0,0,0.0}, {1,1,1.0}, ... };
But that wasn't possible. So though I know that structs are value types, I concluded that this is only true when passing them as parameters to function, and I had to use new, like this (using structs here):
struct SomeStruct {
int a, b;
double c;
SomeStruct (int a, int b, double c) {
this.a = a; this.b = b; this.c = c;
}
}
SomeStruct[] a = new SomeStruct [1000] {
new SomeStruct {0,0,0.0},
new SomeStruct {1,1,1.0},
...
};
You can use the struct keyword in C#. C# structs are value types- an array of structs is contiguously stored structs, identical to a C++ standard array.
It's ugly, but this will work (if you change the type to struct instead of class)
SomeStruct[] a = new SomeStruct [1000];
a[0].val1 = 0;
a[0].val2 = 1;
a[0].val3 = 2.0;
...
a[999].val1 = 0;
a[999].val2 = 1;
a[999].val3 = 2.0;
Edit:
If this is a global field, declare a as static readonly.
You can do this by creating a new collection for SomeStruct (derived from IEnumerable<>) Each item you use in the initialization syntax gets converted to a call to .Add(...), so provided your collection class has a method called Add (doesn't need to inherit from any other interface for this), with matching arguments, you can use the same C++ syntax.
eg.
public class SomeStructCollection : IEnumerable<SomeStruct> {
private readonly SomeStruct[] someStructs = new SomeStruct[1000];
private int currentIndex;
public void Add(int val1, int val2, double val3) {
someStructs[currentIndex++] = new SomeStruct(val1, val2, val3);
}
public SomeStruct this[int index] {
get { return someStructs[index];
}
//Implement IEnumerable<> interface.
}
Calling code can then wrap values in some blocks
SomeStructCollection coll = new SomeStructCollection {
{0, 0, 0.0}, {1, 1, 1.0}, { ... },
};