NoSkillPureAndy
NoSkillPureAndy
CC#
Created by NoSkillPureAndy on 6/23/2023 in #help
✅ Writing a scuffed way to use an "assignment" (=) operator
Obviously, there's no such thing as an assignment operator. I'd like to find some way around that. I have a class that looks something like this:
struct MyType<T> {
public int AField;
public T Value {
get {
// Stuff to do with AField
}
set {
// Stuff to do with AField
}
}

public Type<T>(int aField) {
AField = aField;
}
}
struct MyType<T> {
public int AField;
public T Value {
get {
// Stuff to do with AField
}
set {
// Stuff to do with AField
}
}

public Type<T>(int aField) {
AField = aField;
}
}
I'd like to be able to assign values to this:
MyType<float> myType = new(20);

// What I want:
myType = 30.5f;
// What I have to do at the moment:
myType.Value = 30.5f;
MyType<float> myType = new(20);

// What I want:
myType = 30.5f;
// What I have to do at the moment:
myType.Value = 30.5f;
Is there any hacky, bodged, whatever way of doing this? I can't do it like this, obviously, because operators are static:
public static implicit operator MyType<T>(T value) {
MyType<T> ret = new(this.AField);
ret.Value = value;
return ret;
}
public static implicit operator MyType<T>(T value) {
MyType<T> ret = new(this.AField);
ret.Value = value;
return ret;
}
Any ideas are appreciated, thanks!
21 replies
CC#
Created by NoSkillPureAndy on 11/9/2022 in #help
How would I check if a generic type is unmanaged, then pass it to a method with where T ; unmanaged?
I have a method that needs to call different methods based on whether T is managed or not. I'm not sure how to check if T is unmanaged, and also tell the compiler that it can use it in the method with the unmanaged constraint.
public unsafe T SomethingUnmanaged<T>(int stuff) where T : unmanaged
{
//do something
return whatever;
}
public unsafe T SomethingManaged<T>(int stuff)
{
//do something different
return whatever;
}
public unsafe T Something<T>(int stuff)
{
if (T is unmanaged)
return SomethingUnmanaged<T>(stuff);
else
return SomethingManaged<T>(stuff);
}
public unsafe T SomethingUnmanaged<T>(int stuff) where T : unmanaged
{
//do something
return whatever;
}
public unsafe T SomethingManaged<T>(int stuff)
{
//do something different
return whatever;
}
public unsafe T Something<T>(int stuff)
{
if (T is unmanaged)
return SomethingUnmanaged<T>(stuff);
else
return SomethingManaged<T>(stuff);
}
5 replies