[Proposal] Generic properties #4764
Unanswered
differentrain
asked this question in
Language Ideas
Replies: 1 comment 1 reply
-
Why not making your struct generic - something like: using System;
Union32<int> union = new() { Value = 42 };
Console.WriteLine(union.Value);
var other = union.AsSomethingElse<TwoShorts>();
Console.WriteLine(other.Value.Part1);
Console.WriteLine(other.Value.Part2);
ref var refReinterpret = ref union.AsSomethingElseRef<int, TwoShorts>();
refReinterpret.ValueRef.Part1++;
Console.WriteLine(union.Value);
public struct Union32<T> where T : unmanaged
{
private unsafe fixed byte _buffer[32];
public ref T ValueRef
{
get
{
unsafe
{
fixed (void* p = _buffer)
return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(p);
}
}
}
public T Value
{
get => ValueRef;
set => ValueRef = value;
}
public Union32<X> AsSomethingElse<X>() where X : unmanaged
{
return this.AsSomethingElseRef<T, X>();
}
}
public static class Union32Ext
{
public static ref Union32<To> AsSomethingElseRef<From, To>(
this ref Union32<From> me)
where To : unmanaged
where From : unmanaged
{
return ref System.Runtime.CompilerServices.Unsafe.As<Union32<From>, Union32<To>>(ref me);
}
}
struct TwoShorts
{
public short Part1;
public short Part2;
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
This feature is just like generic method, and often used by low-level developers.
Motivation
Consider a Union in C language.
In modern C#, It is very easy to implement a type plays the same role as
Union
.e.g.
It is not concise enough for invoker, so how about using generic properties?
Design
Generic properties will never support auto-implemented properties.
This feature is dependent on additional logic provides ways to access shared object.
A Generic property may have a
set
accessor and aget
accessor.A Generic property may only have a
get
accessor.Obviously, in some case we can write this code:
public T Value<T> where T : unmanaged => // todo
Exploration: every accessor uses different constraint
I have no idea about it, and I don't know if it is useful.
Or generic accessors? I do not think it's a friendly feature, I do not like it, for discussion only.
get
accessors only:·Or·
public TGetter Value where TGetter : unmanaged => // todo
Beta Was this translation helpful? Give feedback.
All reactions