Class template with value in C# - c#

Is there any type of template that can be used like the statement below:
BitSet<10> bitSet; //we can create bitset with n bits, here is 10
bool b = bitSet.get<3>(); //get value of bit 3rd.
And how can I define a class like this in C#?

You should use a simple class, with a Constructor parameter (10) and then just call any method that recall any bit. Templates are for datatypes afaik. Anyway, look at This answer to verify if thats what you are looking for (Constructor parameter with a template with a given type)

c# code is :
bool[] array = new bool[]{true,false,false,true,false,false};
System.Collections.BitArray bitArray = new System.Collections.BitArray(array);
Console.WriteLine(bitArray[3]);

Not exactly like what you want but you can do that kind of stuff by using Indexers.
class BitSet
{
private bool[] _bits;
public BitSet(int length)
{
_bits = new bool[length];
}
public bool this[int index]
{
get
{
return _bits[index];
}
set
{
_bits[index] = value;
}
}
}
To use that class
BitSet bitset = new BitSet(10);
bitset[0] = true;
Console.WriteLine(bitset[0]);

Related

Can someone explain this C# syntax?

What's actually going on here:
public decimal[] Coefficients;
public decimal this[int i]
{
get { return Coefficients[i]; }
set { Coefficients[i] = value; }
}
What does the this serve as? Is it some sort of extension to the decimal?
It's an Indexer.
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
Example from the linked MSDN:
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
// Define the indexer, which will allow client code
// to use [] notation on the class instance itself.
// (See line 2 of code in Main below.)
public T this[int i]
{
get
{
// This indexer is very simple, and just returns or sets
// the corresponding element from the internal array.
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer.
class Program
{
static void Main(string[] args)
{
// Declare an instance of the SampleCollection type.
SampleCollection<string> stringCollection = new SampleCollection<string>();
// Use [] notation on the type.
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
// Output:
// Hello, World.
It is an indexer it will be called when you use syntax like obj[1]. https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx
Have you ever wondered how List<T>'s myList[i] works in c# just like an array ?
The Answer is in your question. The syntax you posted is a syntactic sugar that the compiler transforms into properties called get_Item(int index) and set_Item(int index, decimal value). It is used in List<T> for example to access the internal array used in the class and return the element at the specified index (set or get). This feature is called an Indexer.
To test that yourself, try to create a method with same signature :
public decimal get_Item(int i)
{
return 0;
}
You'll get a compiler error :
Error CS0082: Type 'MyClass' already reserves a member called
'get_Item' with the same parameter types

How to return enum from property

Is there a way how to return full enum by property? Here is example of what I want to do:
// MyEnums.cs
public enum Languages
{
cs = 0,
pl = 1,
en = 2,
de = 3,
}
// General.cs
public static MyEnums.Languages Languages
{
get
{
return MyEnums.Languages;
}
}
enum is a type, i guess you actually want to get all enum-values. You could use this wrapper:
public static class EnumWrapper<T> where T : struct
{
public static T[] Values
{
get
{
Type ofT = typeof(T);
if (!ofT.IsEnum) throw new ArgumentException("Must be enum type");
return Enum.GetValues(ofT).Cast<T>().ToArray();
}
}
}
// ...
Languages[] languages = EnumWrapper<Languages>.Values;
If you want to return all available values defined in the enum, you can use
Enum.GetValues(typeof(MyEnums.Languages));
and modify your method so it returns a MyEnums.Languages[] (or a List<MyEnums.Languages>, which is always easier to manage for calling code)
To get all values in the enum, use Enum.GetValues. You might also want to cast it back to the correct type:
Languages[] languages = Enum.GetValues(typeof(Languages)).Cast<Languages>().ToArray();
// languages is an array containing { Languages.cs, Languages.pl, Languages.en, Languages.de }

instance of class C#

I am pretty new to C# programming so sorry for dumb questions.
I set up DeviceInfos class, which I like to use every loop. So at the end I like to have so many "the same" classes, how many is "nod"´s.
I nicely defined new Instance of my DeviceInfos class, but without "indexing support" :) How to fix this?
My public class DeviceInfos:
public class DeviceInfos
{
public bool boolSerialNumber;
public byte[] byteSerialNumber;
public string stringSerialNumber;
public bool boolManufacturer;
public byte[] byteManufacturer;
public string stringManufacturer;
public bool boolProduct;
public byte[] byteProduct;
public string stringProduct;
public HidDeviceData.ReadStatus ReadStatus { get; set; }
public bool boolWriteNameSuccess;
public bool boolReadNameSuccess;
public string stringName;
And code where comes to error:
DeviceInfos _deviceInfo = new DeviceInfos();
for (nod = 0; nod < _deviceList.Length; nod++)
{
_deviceInfo[nod].boolSomething= false;
_deviceInfo[nod].boolSomething = _deviceList[nod].ReadSerialNumber(out _deviceInfo[nod].byteSerialNumber);
...
Error Acoour: An unhandled exception of type 'System.NullReferenceException' occurred in USBmiddlewareDeveloping.exe
This happend in row
_deviceInfo[nod].boolSerialNumber = false;
Why? Or how to do it?
Apparently you need to declare an array of your structs:
DeviceInfos[] _deviceInfos = new DeviceInfos[_deviceList.Length];
for (nod = 0; nod < _deviceList.Length; nod++)
{
_deviceInfos[nod] = new DeviceInfos();
_deviceInfo[nod].boolSomething= false;
...
And consider renaming your struct to DeviceInfo if it only represents a single device. Also, as already commented, consider making it a class, not a struct.
As D Stanley suggested, a class is likely what you need. There are several enumerable classes built-in to the language, such as List< T >() (T is the generic denotation for an object, such as a DeviceInfo class). List is my personal favorite; I prefer lists for their LINQ functions and the ability to add and remove objects easily. You could have:
var deviceInfos = new List<DeviceInfo>();
for(var nod = 0; nod < deviceInfos.Count; nod++)
{
var deviceInfo = deviceInfos[nod];
byte[] byteSerialNumber;
deviceInfo.boolSomething = deviceInfo.ReadSerialNumber(out byteSerialNumber);
deviceInfo.byteSerialNumber = byteSerialNumber;
}
Your quesition is vague one; in case you want to create an array from list
you can use Linq:
DeviceInfo[] _deviceInfo = _deviceList // <- source
.Select(item => new DeviceInfo() { // <- data representation
boolSomething = false,
someOther = item.someOtherData,
...
})
.ToArray(); // <- finally to array
If you need indexing support for your struct, check this out:
https://msdn.microsoft.com/en-us/library/2549tw02.aspx
In your struct, something like:
public YourType this[int index]
{
get
{
return yourList[index];
}
set
{
yourList[index] = value;
}
}

What is the best way to implement a Rust enum in C#?

I have an entity that can be in one of different states (StateA, StateB and StateC), and in each of them have relevant data of distinct types (TStateA, TStateB, TStateC). Enums in Rust represent this perfectly. What is the best way to implement something like this in C#?
This question may appear similar, but enums in Rust and unions in C are significantly different.
You need a class to represent your Entity
class Entity {States state;}
Then you need a set of classes to represent your states.
abstract class States {
// maybe something in common
}
class StateA : MyState {
// StateA's data and methods
}
class StateB : MyState {
// ...
}
Then you need to write code like
StateA maybeStateA = _state as StateA;
If (maybeStateA != null)
{
- do something with the data in maybeStateA
}
C# does not have a nice way of writing code for this yet, maybe the Pattern Matching that is being considered for C#.next would help.
I think you should rethink your design to use object relationships and containment, trying to take a design that works in rust and force it into C# may not be the best option.
This might be crazy, but if you are hard-up about emulating Rust-like enums in C#, you could do it with some generics. Bonus: you keep type-safety and also get Intellisense out of the deal! You'll lose a little flexibility with various value types, but I think the safety is probably worth the inconvenience.
enum Option
{
Some,
None
}
class RustyEnum<TType, TValue>
{
public TType EnumType { get; set; }
public TValue EnumValue { get; set; }
}
// This static class basically gives you type-inference when creating items. Sugar!
static class RustyEnum
{
// Will leave the value as a null `object`. Not sure if this is actually useful.
public static RustyEnum<TType, object> Create<TType>(TType e)
{
return new RustyEnum<TType, object>
{
EnumType = e,
EnumValue = null
};
}
// Will let you set the value also
public static RustyEnum<TType, TValue> Create<TType, TValue>(TType e, TValue v)
{
return new RustyEnum<TType, TValue>
{
EnumType = e,
EnumValue = v
};
}
}
void Main()
{
var hasSome = RustyEnum.Create(Option.Some, 42);
var hasNone = RustyEnum.Create(Option.None, 0);
UseTheEnum(hasSome);
UseTheEnum(hasNone);
}
void UseTheEnum(RustyEnum<Option, int> item)
{
switch (item.EnumType)
{
case Option.Some:
Debug.WriteLine("Wow, the value is {0}!", item.EnumValue);
break;
default:
Debug.WriteLine("You know nuffin', Jon Snow!");
break;
}
}
Here's another sample demonstrating the use of a custom reference type.
class MyComplexValue
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public override string ToString()
{
return string.Format("A: {0}, B: {1}, C: {2}", A, B, C);
}
}
void Main()
{
var hasSome = RustyEnum.Create(Option.Some, new MyComplexValue { A = 1, B = 2, C = 3});
var hasNone = RustyEnum.Create(Option.None, null as MyComplexValue);
UseTheEnum(hasSome);
UseTheEnum(hasNone);
}
void UseTheEnum(RustyEnum<Option, MyComplexValue> item)
{
switch (item.EnumType)
{
case Option.Some:
Debug.WriteLine("Wow, the value is {0}!", item.EnumValue);
break;
default:
Debug.WriteLine("You know nuffin', Jon Snow!");
break;
}
}
This looks a lot like Abstract Data Types in functional languages. There's no direct support for this in C#, but you can use one abstract class for the data type plus one sealed class for each data constructor.
abstract class MyState {
// maybe something in common
}
sealed class StateA : MyState {
// StateA's data and methods
}
sealed class StateB : MyState {
// ...
}
Of course, there's nothing prohibiting you from adding a StateZ : MyState class later, and the compiler won't warn you that your functions are not exhaustive.
Just from the back of my head, as a quick implementation...
I would first declare the Enum type and define enumerate items normally.
enum MyEnum{
[MyType('MyCustomIntType')]
Item1,
[MyType('MyCustomOtherType')]
Item2,
}
Now I define the Attribute type MyTypeAttribute with a property called TypeString.
Next, I need to write an extension method to extract the Type for each enum item (first in string, then later reflect to real type):
public static string GetMyType(this Enum eValue){
var _nAttributes = eValue.GetType().GetField(eValue.ToString()).GetCustomAttributes(typeof (MyTypeAttribute), false);
// handle other stuff if necessary
return ((MyTypeAttribute) _nAttributes.First()).TypeString;
}
Finally, get the real type using reflection...
I think the upside of this approach is easy to use later in the code:
var item = MyEnum.SomeItem;
var itemType = GetType(item.GetMyType());
I've been looking into Rust recently and been thinking the same questions. The real problem is the absence of the Rust deconstruction pattern matching but the type itself is long-winded but relatively straightforward if you are willing to use boxing:
// You need a new type with a lot of boilerplate for every
// Rust-like enum but they can all be implemented as a struct
// containing an enum discriminator and an object value.
// The struct is small and can be passed by value
public struct RustyEnum
{
// discriminator type must be public so we can do a switch because there is no equivalent to Rust deconstructor
public enum DiscriminatorType
{
// The 0 value doesn't have to be None
// but it must be something that has a reasonable default value
// because this is a struct.
// If it has a struct type value then the access method
// must check for Value == null
None=0,
IVal,
SVal,
CVal,
}
// a discriminator for users to switch on
public DiscriminatorType Discriminator {get;private set;}
// Value is reference or box so no generics needed
private object Value;
// ctor is private so you can't create an invalid instance
private RustyEnum(DiscriminatorType type, object value)
{
Discriminator = type;
Value = value;
}
// union access methods one for each enum member with a value
public int GetIVal() { return (int)Value; }
public string GetSVal() { return (string)Value; }
public C GetCVal() { return (C)Value; }
// traditional enum members become static readonly instances
public static readonly RustyEnum None = new RustyEnum(DiscriminatorType.None,null);
// Rusty enum members that have values become static factory methods
public static RustyEnum FromIVal(int i)
{
return new RustyEnum(DiscriminatorType.IVal,i);
}
//....etc
}
Usage is then:
var x = RustyEnum::FromSVal("hello");
switch(x.Discriminator)
{
case RustyEnum::DiscriminatorType::None:
break;
case RustyEnum::DiscriminatorType::SVal:
string s = x.GetSVal();
break;
case RustyEnum::DiscriminatorType::IVal:
int i = x.GetIVal();
break;
}
If you add some extra public const fields this could be reduced to
var x = RustyEnum::FromSVal("hello");
switch(x.Discriminator)
{
case RustyEnum::None:
break;
case RustyEnum::SVal:
string s = x.GetSVal();
break;
case RustyEnum::IVal:
int i = x.GetIVal();
break;
}
... but you then need a different name for creating the valueless members (like None in this example)
It seems to me that if the C# compiler was to implement rust enums without changing the CLR then this is the sort of code that it would generate.
It would be easy enough to create a .ttinclude to generate this.
Deconstruction is not as nice as Rust match but there is no alternative that is both efficient and idiot proof (the inefficient way is to use something like
x.IfSVal(sval=> {....})
To summarize my rambling - It can be done but it's unlikely to be worth the effort.
Short answer you can't. Even if you feel you can just don't do it you would shoot yourself in foot in doing so. We'll have to wait for the C# team to come up with a type with something like below
struct lives on stack in most cases this means it has a fixed size in memory
What we are expecting is sort of multiple struct with different layout but still fits in one decided stack of memory. The way rust handles this is by using the memory size of largest of the group for example
# Right now:
struct A { int a } # 4 bytes
struct B { int a, int b } # 8 bytes
# Can do but highly don't recommend would be waste of precious time, memory and cpu
struct AB {
A a,
B b
} # 12 bytes + 2 bytes to keep bool to check which struct should be used in code
# Future/Should be
super struct AB {
A(int),
B(int, int)
} # 8 bytes
Never did anything in Rust, but looking at the docs it seams to me that you would have to implement a textbook C# class. Since Rust enums even support functions and implementations of various types.
Probabily an abstract class.

Is it possible to change default value for value types variables? [duplicate]

This question already has answers here:
Is it possible to change the default value of a primitive data type?
(6 answers)
Closed 7 years ago.
I'm just curious to know, is it possible to change default value of e.g. int in C# and I can have a value -1 instead of 0.
public class Foo {
public int i;
}
...
foo = new Foo();
Console.Write(foo.i);
so this code must return
-1
Without explicit initializing
public class Foo {
public int i = -1;
}
Can I always be sure, that someone don't print somewhere something like
#define TRUE FALSE
but for default value of int
P.S. for interest purposes only.
No, basically. Assuming you don't initialize fields, the memory space is simply zeroed. You shouldn't expose fields directly anyway.
One trick I have seen to get around this (used by the capnp serializer, which works against raw memory, not objects) is to use xor. For example: if the default is -1, you can xor the value in and out:
public class Foo {
private int i;
public int I {
get { return i ^ -1; }
set { i = value ^ -1; }
}
}
This has no initialization, and does what you want. For use with types other than bools and integers this is more complex, but still possible - but it would be easier to use an initializer.
Note that for the -1 case, you could use "not" rather than "xor":
public class Foo {
private int i;
public int I {
get { return ~i; }
set { i = ~value; }
}
}
However: a field initializer (int i = -1;) or a constructor (public Foo() { i = -1; }) is probably simpler.
You can't change int's default value, but you can set Foo's variables default value:
public class Foo
{
public int i;
public Foo()
{
i = -1;
}
}
As far as I know, you can not change the default value of value types.
But you can certainly initialize it to a value you want.
for eg.
public class Foo {
public int i = -1;
}
...
foo = new Foo();
Console.Write(foo.i);
it will return
-1
A nice solution would be to override default(T), but you can't override this keyword. It is always null for reference types and zero for value types.

Categories

Resources