typedef emulation in C# - c#

I have a field variable named uid in a class. The type is int, but I want to open the possibility that I change it long or short.
With C++, typedef is the one for this purpose, but I see C# doesn't have typedef.
Is there a way to mimic typedef in C#?

I think you're trying to alias the type. If so, you can alias it via the using alias directive. You must specify the fully qualified type (the entire namespace) when assigning an alias.
For example:
using System;
using MyAlias = System.Int32;
namespace UsingAlias
{
class Program
{
static void Main(string[] args)
{
MyAlias temp = Math.Min(10, 5);
Console.WriteLine(temp);
MyAlias result = MyAlias.Parse("42");
Console.WriteLine(result);
}
}
}

Try making a class. It's like a typedef on steroids, and you can change the internal representation as much as you want without affecting the interface!
You could even make it a guid!

Make it a struct:
struct Uid { public int Value; }

Encapsulate it in it's own class (or a struct, if more appropriate).
public class UID
{
public int Value { get; set; }
}
Write your methods in terms of your UID class, limiting the exposure to the actual value type to the smallest subset of code necessary.
publc class Entity
{
public UID ID { get; set; }
public void Foo( UID otherID )
{
if (otherID.Value == this.ID.Value)
{
...
}
}
}
}

Define a struct with just one field
public struct ID_Type
{
public long Id;
};
and use it whereever you need it.
If you have just one class where the ID type is needed, you can also try to make this class a generic class with the UID type being a type parameter.

You could always use generics:
public class Foo<T>
{
public T MyField { get; set; }
}
public class FooInt : Foo<int>
{
}
public class FooShort : Foo<short>
{
}
or, just change it later on.
/// want an int
public class Foo
{
public int MyField { get; set; }
}
/// and just change it later on:
public class Foo
{
public short MyField { get; set; }
}

Wouldn't the result be the same if you used int and then changed it later on?

See this , he uses Operator Overloading
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/019a258e-8d50-4a9f-b0ef-8311208ebb6a/

Here is a simple solution that helped.
using typedef = System.Int32;
class MyTypeDef
{
typedef ERROR, TRUE=1, FALSE=0;
public int MyMethod()
{
if(this is an error condition)
{
ERROR = TRUE;
}
else
{
ERROR = FALSE;
}
return ERROR;
} // end MyMethod
} // end MyTypeDef

Is there a way to mimic typedef in C#
No
to solve my problem
What problem?

Related

This way of using struct puzzled me

As I know before using a struct , I must have a object of it. Then I can't understand the following codes. Maybe the problem is somewhere else I can't find. Please help me.
namespace Ixxat.Vci3.Bal.Can
{
public struct CanBitrate
{
.....
public static CanBitrate Cia10KBit { get; }
public static CanBitrate Cia125KBit { get; }
public static CanBitrate Cia20KBit { get; }
public static CanBitrate Cia250KBit { get; }
public static CanBitrate Cia500KBit { get; }
public static CanBitrate Cia50KBit { get; }
public static CanBitrate Cia800KBit { get; }
// Gets an array of all available CiA baud rates.
public static CanBitrate[] CiaBitRates { get; }
// Gets a empty bit timing value.
public static CanBitrate Empty { get; }
public string Name { get; }
public override sealed string ToString();
}
}
Abrove all is the given interface, I think the "Cia125KBit" is a function of the struct. Then in another file, there is a function like this:
mCanCtl.InitLine( CanOperatingModes.Standard | CanOperatingModes.ErrFrame
, CanBitrate.Cia125KBit);
the definition of the InitLine is as follows:
public interface ICanControl : ICanSocket
{
...
void InitLine(CanOperatingModes operatingMode, CanBitrate bitrate);
}
My question is , CanBitrate is the name of struct, why it can be used in the function like CanBitrate.Cia125KBit? As I learned, It should like this
CanBitrate a;
a.Can125KBit;
I think there must something I am unknown or misunderstand . Ask for help.
Cia125KBit is a static member which means that it can be accessed without creating an instance of the struct. As MSDN puts it,
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.
To contrast this, the member Name is not declared as static. Therefore, trying to do something like CanBitRate.Name would throw an error.
The thing you're missing is the keyword static. A method, property or field of a class can be declared static to decouple it from individual instances, meaning that it's accessed through the class itself as opposed to objects.
It's because Cia125KBit is a static member. Static members are not bound to any instance and can be accessed only via class/struct name.

Generic Interface type conversion issues

I have been battling with this bit of code for a while now and I am trying to get a solution as it is literally the last part before it goes to testing.
I have the following interfaces and classes (simplified to the relevant parts):
public interface ITagParent<T> where T : ITag
{
List<TagAddOn<T>> TagCollection { get; set; }
}
public interface ITag
{
int Id { get; set; }
string Description { get; set; }
TagGroup TagGroup { get; set; }
}
public class TagAddOn<T> : ViewModelBase where T : ITag
{
private T _currentTag;
public T CurrentTag
{
get { return _currentTag; }
set { _currentTag = value; }
}
}
public partial class Customer : ITagParent<CustomerTag>
{
List<TagAddOn<CustomerTag>> _tagCollection;
public List<TagAddOn<CustomerTag>> TagCollection
{
get { return _tagCollection; }
set { _tagCollection = value; }
}
}
public partial class CustomerTag : ITag
{
public int Id { get; set; }
}
public class TagAddOnManager
{
public static string GetTagCurrentValue(List<TagAddOn<ITag>> dataObjectAddOns)
{
// LOTS OF SNIPPING!
return string.Empty;
}
}
I am trying to use the GetTagCurrentValue method in the TagAddOnManager class like this:
string value = TagAddOnManager.GetTagCurrentValue(
((ITagParent<ITag>)gridCell.Row.Data).TagCollection));
Everything compiles fine, but errors when trying to cast gridCell.Row.Data to ITagParent<ITag>. I understand this is due to covarience and a workaround (if not a terribly safe one) is to mark T in the ITagParent interface with the out keyword, but that won't work as you can see it is used in the TagCollection property, which can't be read only.
I tried casting the above to ITagParent<CustomerTag>, but this fails at compile time with a 'cannot convert' error when trying to feed it into my GetTagCurrentValue method.
Another option I considered is using some base classes instead of the ITagParent interface, but that won't work as the Customer object already inherits from another base class, which can't be modified for this implementation.
I know I could just overload the GetTagCurrentValue method with List<TagAddOn<CustomerTag>> as the parameter type and all other variations, but that really seems like a 'I give up' solution. I could probably use reflection to get the desired results, but that would be unwieldy and not very efficient, especially considering this method could be called a lot in a particular process.
So does anyone have any suggestions?
Could you use something like that
public class TagAddOnManager
{
public static string GetTagCurrentValue<TTag>(ITagParent<TTag> tagParent)
where TTag : ITag
{
// Just an example.
return tagParent.TagCollection.First().CurrentTag.Description;
}
}
and use it like that?`
var value = TagAddOnManager.GetTagCurrentValue((Customer)CustomergridCell.Row.Data);

How to inherit a static property with a unique value for each subclass?

I have a series of objects, lets call them buildings, that each share certain properties that are static for that building, but different for each building, such as price. I assumed that the best way to implement this was to create an abstract superclass with the shared price attribute and set the values in each subclass, but I cannot figure out how to get this to work. Here is an example of something I have tried:
using System;
public abstract class Buildings
{
internal static int price;
internal static int turnsToMake;
}
using System;
public class Walls : Buildings
{
public Walls()
{
price = 200;
turnsToMake = 5;
}
}
This works fine for construction, but if I want to check the price before creating it (to check if the player has enough money) then it just returns a null value. I'm sure that it is is a super simple fix, but I can't figure it out. Any help?
There is a "patchy" yet simple solution that's worth to consider. If you define your base class as a Generic class, and in deriving classes set T as the class itself, It will work.
This happens because .NET statically defines a new type for each new definition.
For example:
class Base<T>
{
public static int Counter { get; set; }
public Base()
{
}
}
class DerivedA : Base<DerivedA>
{
public DerivedA()
{
}
}
class DerivedB : Base<DerivedB>
{
public DerivedB()
{
}
}
class Program
{
static void Main(string[] args)
{
DerivedA.Counter = 4;
DerivedB.Counter = 7;
Console.WriteLine(DerivedA.Counter.ToString()); // Prints 4
Console.WriteLine(DerivedB.Counter.ToString()); // Prints 7
Console.ReadLine();
}
}
Don't use static. Static says that all instances of Building have the same value. A derived class will not inherit its own copy of the statics; but would always modify the base class statics. In your design there would only be one value for price and turnsToMake.
This should work for you:
public abstract class Buildings
{
internal int price;
internal int turnsToMake;
}
However, most people don't like using fields these days and prefer properties.
public abstract class Buildings
{
internal int Price { get; set; }
internal int TurnsToMake { get; set; }
}
I want to check the price before creating it […]
I suppose that's how you got to static fields; however, static and virtual behaviour cannot be combined. That is, you would have to re-declare your static fields for each subclass. Otherwise, all your subclasses share the exact same fields and overwrite each others' values.
Another solution would be to use the Lazy<T, TMetadata> type from the .NET (4 or higher) framework class library:
public class Cost
{
public int Price { get; set; }
public int TurnsToMake { get; set; }
}
var lazyBuildings = new Lazy<Buildings, Cost>(
valueFactory: () => new Walls(),
metadata: new Cost { Price = 200, TurnsToMake = 5 });
if (lazyBuildings.Metadata.Price < …)
{
var buildings = lazyBuildings.Value;
}
That is, the metadata (.Metadata) now resides outside of the actual types (Buildings, Walls) and can be used to decide whether you actually want to build an instance ( .Value) of it.
(Thanks to polymorphism, you can have a whole collection of such "lazy factories" and find a building type to instantiate based on the metadata of each factory.)
Building on Uri Abramson's answer above:
If you need to access the static property from within the Base class, use reflection to get the value from T. Also, you can enforce that Base must be inherited using T of the derived type.
e.g.
class Base<T> where T : Base <T> {
static int GetPropertyValueFromDerivedClass<PropertyType>(BindingFlags Flags = BindingFlags.Public | BindingFlags.Static, [CallerMemberName] string PropertyName = "")
{
return typeof(T).GetProperty(PropertyName, Flags)?.GetValue(null);
}
static int Counter{ get => GetPropertyValueFromDerivedClass(); }
}
static int DoubleCounter{ return Counter*2; } //returns 8 for DerivedA and 14 for DerivedB
}
If you have a better way to do this, please post.
Not as easy for the inheritor, but workable...
public abstract class BaseType
{
public abstract contentType Data { get; set; }
}
public class InheritedType : BaseType
{
protected static contentType _inheritedTypeContent;
public override contentType Data { get => _inheritedTypeContent; set => _inheritedTypeContent = value; }
}

No base class problem, How to use Castle.DynamicProxy Mixin in this particular case?

I have a 3rd party badly designed library that I must use.
It has all sorts of types it works with, we'll call them SomeType1, SomeType2 etc.
None of those types share a common base class but all have a property named Value with a different return type.
All I want to do is to be able to Mixin this class so I'll be able to call someType1Instance.Value and someType2Instance.Value without caring what the concreate type it is and without caring what the return type is (I can use object).
So my code is currently:
public interface ISomeType<V>
{
V Value {get; set;}
}
public interface ISomeTypeWrapper
{
object Value { get; set; }
}
public class SomeTypeWrapper<T> : ISomeTypeWrapper
where T : ISomeType<???>
{
T someType;
public SomeTypeWrapper(T wrappedSomeType)
{
someType = wrappedSomeType
}
public object Value
{
get { return someType.Value; }
set { someType.Value = value != null ? value : default(T); }
}
}
public class SomeType1
{
public int Value { get; set; }
}
public class SomeType2
{
public string Value { get; set; }
}
The problem is that I don't know what T might be until runtime due to the fact that I get a dictionary of objects.
I can iterate the dictionary and use reflection to create a SomeWrapperType on runtime but I would like to avoid it.
How can I mixin the concreate type of SomeType to ISomeType?
How can I know what V type parameter is? (wish I had typedefs and decltype like in c++)
How can I, with the minimum of use of reflection possible Mixin those classes with the interface/base class?
You could try the Duck Typing Extensions for Windsor. It means you will need to register each of your types.
container
.Register(Component.For(typeof(SomeType1)).Duck<ISomeType>())
.Register(Component.For(typeof(SomeType2)).Duck<ISomeType>());
You could probably use linq and the register AllTypes syntax to reduce code if the names are similar.
Alternatively in the short term create a factory which can return you the objects you need, implement a concrete object for each type. No you are using the interface you can remove the factory at a later date and replace it with something else with minimal impact:
public class SomeTypeWrapperFactory
{
public ISomeType<int> CreateWrapper(SomeType1 someType1)
{
return new SomeType1Wrapper(someType1);
}
public ISomeType<string> CreateWrapper(SomeType2 someType2)
{
return new SomeType2Wrapper(someType2);
}
}
public class SomeType1Wrapper : ISomeType<int> { ... }
public class SomeType2Wrapper : ISomeType<int> { ... }
Regardless of how you implement the wrapper, be the individually or using a god like class you have the ability to change how the wrapping is done and keep the rest of your code clean.
Why SomeTypeWrapper but not SomeObjectWrapper?
public class SomeObjectWrapper : ISomeType
{
Object _someObject;
PropertyInfo _valuePropertyInfo;
public SomeObjectWrapper(Object wrappedSomeObject)
{
_someObject = wrappedSomeObject;
_valuePropertyInfo = _someObject.GetType().GetProperty("Value", System.Reflection.BindingFlags.Public);
}
public object Value
{
get { return _valuePropertyInfo.GetValue(_someObject, null); }
set { _valuePropertyInfo.SetValue(_someObject, value, null); }
}
}
Edited With .NET 3.5 using LinFu
You may use LinFu instead of Castle. However, you would be using reflection anyway, both with Castle's and with Linfu's DynamicProxy, only hidden in the guts of the libraries instead of being exposed in your code. So if your requirement to avoid the use of reflection is out of performance concerns, you wouldn't really avoid it with this solution.
In that case I would personally choose Orsol's solution.
However: here's an example with LinFu's ducktyping.
public interface ISomeType {
object Value{get; set;}
}
public class SomeType1
{
public int Value { get; set; }
}
public class SomeType2
{
public string Value { get; set; }
}
public class SomeTypeWrapperFactory
{
public static ISomeType CreateSomeTypeWrapper(object aSomeType)
{
return aSomeType.CreateDuck<ISomeType>();
}
}
class Program
{
public static void Main(string[] args)
{
var someTypes = new object[] {
new SomeType1() {Value=1},
new SomeType2() {Value="test"}
};
foreach(var o in someTypes)
{
Console.WriteLine(SomeTypeWrapperFactory.CreateSomeTypeWrapper(o).Value);
}
Console.ReadLine();
}
}
Since you don't know the type of the SomeType's until runtime, I would not use mixins, but the visitor pattern (I know this doesn't answer the question on how to use mixins for this, but I just thought I'd throw in my 2 cents).
With .NET 4 using dynamic
See Bradley Grainger's post here on using c#4's dynamic keyword to implement the visitor pattern.
In your case, reading all the "Value" properties from your dictionary of SomeType's could work like this:
public class SomeType1
{
public int Value { get; set; }
}
public class SomeType2
{
public string Value { get; set; }
}
public class SomeTypeVisitor
{
public void VisitAll(object[] someTypes)
{
foreach(var o in someTypes) {
// this should be in a try-catch block
Console.WriteLine(((dynamic) o).Value);
}
}
}
class Program
{
public static void Main(string[] args)
{
var someTypes = new object[] {
new SomeType1() {Value=1},
new SomeType2() {Value="test"}
};
var vis = new SomeTypeVisitor();
vis.VisitAll(someTypes);
}
}

C# Automatic Properties - Why Do I Have To Write "get; set;"?

If both get and set are compulsory in C# automatic properties, why do I have to bother specifying "get; set;" at all?
Because you might want a read-only property:
public int Foo { get; private set; }
Or Write-only property:
public int Foo { private get; set; }
ERROR: A property or indexer may not be passed as an out or ref parameter
If you didn't specify {get; set;} then the compiler wouldn't know if it's a field or a property.
This is important becasue while they "look" identical the compiler treats them differently. e.g. Calling "InitAnInt" on the property raises an error.
class Test
{
public int n;
public int i { get; set; }
public void InitAnInt(out int p)
{
p = 100;
}
public Test()
{
InitAnInt(out n); // This is OK
InitAnInt(out i); // ERROR: A property or indexer may not be passed
// as an out or ref parameter
}
}
You shouldn't create public fields/Variables on classes, you never know when you'll want to change it to have get & set accessors, and then you don't know what code you're going to break, especially if you have clients that program against your API.
Also you can have different access modifiers for the get & set, e.g. {get; private set;} makes the get public and the the set private to the declaring class.
Just thought I would share my findings on this topic.
Coding a property like the following, is a .net 3.0 shortcut call “auto-implemented property”.
public int MyProperty { get; set; }
This saves you some typing. The long way to declare a property is like this:
private int myProperty;
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
When you use the “auto-implemented property” the compiler generates the code to wire up the get and set to some “k_BackingField”. Below is the disassembled code using Reflector.
public int MyProperty
{
[CompilerGenerated]
get
{
return this.<MyProperty>k__BackingField;
}
[CompilerGenerated]
set
{
this.<MyProperty>k__BackingField = value;
}
}
disassembled C# code from IL
Also wires up a method for the setter and getter.
[CompilerGenerated]
public void set_MyProperty(int value)
{
this.<MyProperty>k__BackingField = value;
}
[CompilerGenerated]
public int get_MyProperty()
{
return this.<MyProperty>k__BackingField;
}
disassembled C# code from IL
When you declare a read only auto-implemented property, by setting the setter to private:
public int MyProperty { get; private set; }
All the compiler does flag the "set" as private. The setter and getter method say the same.
public int MyProperty
{
[CompilerGenerated]
get
{
return this.<MyProperty>k__BackingField;
}
private [CompilerGenerated]
set
{
this.<MyProperty>k__BackingField = value;
}
}
disassembled C# code from IL
So I am not sure why the framework require both the get; and set; on an auto-implemented property. They could have just not written the set and setter method if it was not supplied. But there may be some compiler level issue that makes this difficult, I don't know.
If you look at the long way of declaring a read only property:
public int myProperty = 0;
public int MyProperty
{
get { return myProperty; }
}
And then look at the disassembled code. The setter is not there at all.
public int Test2
{
get
{
return this._test;
}
}
public int get_Test2()
{
return this._test;
}
disassembled C# code from IL
Because you need some way to distinguish it from plain fields.
It's also useful to have different access modifiers, e.g.
public int MyProperty { get; private set; }
The compiler needs to know if you want it to generate a getter and/or a setter, or perhaps are declaring a field.
If the property didn't have accessors, how would the compiler separate it from a field? And what would separate it from a field?
Well, obviously you need a way of disambiguating between fields and properties. But are required keywords really necessary? For instance, it's clear that these two declarations are different:
public int Foo;
public int Bar { }
That could work. That is, it's a syntax that a compiler could conceivably make sense of.
But then you get to a situation where an empty block has semantic meaning. That seems precarious.
Since no one mentioned it... you could make the auto-property virtual and override it:
public virtual int Property { get; set; }
If there was no get/set, how would it be overridden? Note that you are allowed to override the getter and not the setter:
public override int Property { get { return int.MinValue; } }
Also, because ever since C# 6.0 (in Visual Studio 2015, at the time of this answer available in version Ultimate Preview) you may implement a true read-only property:
public string Name { get; }
public string Name { get; } = "This won't change even internally";
... as opposed to currently imperfect workaround with public getter/private setter pair:
public string Name { get; private set; }
public Constructor() { Name="As initialised"; }
public void Method() { Name="This might be changed internally. By mistake. Or not."; }
Example of the above below (compiled and executable online here).
using System;
public class Propertier {
public string ReadOnlyPlease { get; private set; }
public Propertier() { ReadOnlyPlease="As initialised"; }
public void Method() { ReadOnlyPlease="This might be changed internally"; }
public override string ToString() { return String.Format("[{0}]",ReadOnlyPlease); }
}
public class Program {
static void Main() {
Propertier p=new Propertier();
Console.WriteLine(p);
// p.ReadOnlyPlease="Changing externally!";
// Console.WriteLine(p);
// error CS0272: The property or indexer `Propertier.ReadOnlyPlease' cannot be used in this context because the set accessor is inaccessible
// That's good and intended.
// But...
p.Method();
Console.WriteLine(p);
}
}
Other tasty news about C# 6.0 available as official preview video here.

Categories

Resources