Where to put conversion functions? - c#

As C# lacks support for freestanding functions, I find it hard to find a place to put conversion functions. For example, I'd like to convert an enum to a number. In C++, I would make the following freestanding function for this:
UINT32 ConvertToUint32(const MyEnum e);
How can I elegantly do this in C#? Should I make a dummy static class for holding the function, and if so, how can I find a meaningful name for it? Or should I make a partial class Convert?
Any ideas?
Thanks in advance.
Update: In retrospect, my example was not very well chosen, as there exists a default conversion between enum and int. This would be a better example:
Person ConvertToPerson(const SpecialPersonsEnum e);

The above example looks like a candidate for an Extension Method.
If that's not possible, I define them as static methods in a static class ; I'd normally put them in a static class called XXXHelper

I'd go with:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int ConvertToInt(this MyEnum e)
{
var m;
// ... Implementation
return m;
}
}
}
Then you'd simply use MyEnum.ConvertToInt(); The same can be done for multiple conversions all from within the same class. Extension methods are in a nutshell, damn sexy.
Also, Eric's comment about Type Converters got me googling. Pretty awesome, however I'm not sure how to use them with an Enum, but for other conversions, they're clean as a whistle to implement. Have a look here:
http://www.pluralsight.com/community/blogs/fritz/archive/2005/12/09/17343.aspx

I would recomend that you create and assembly that would contain all your helper methods/constants and enums that will be used in other projects.
This will allow you to easily include this assembly with other assemblies that need it and avoid circular references.

Can't you just use a cast for this? (UInt32)e. Or else call Convert.ToUInt32(e)

The idea of creating a static "dummy class" seems to be what Microsoft suggests:
http://msdn.microsoft.com/en-us/library/bb383974.aspx
I think in your particular example doing a partial class Convert makes the most sense.

I faced the similar problem once and I did this
class Program
{
static void Main(string[] args)
{
string s = "123";
int n = Convert.StringToInt(s);
}
}
class Convert
{
public static int StringToInt(string s)
{
// implementation
}
public static string IntToString(int n)
{
// implementation
}
}

Related

Function 'class' in Unity/C#

I'm new in Unity. My question isa, is it possible to create function files, without constructor and other stuff? In flash actionscript 3 it's look like this:
package util
{
public function getRandomNumber(minQ:Number = 0, maxQ:Number = Number.MAX_VALUE):Number
{
return minQ + Math.random() * (maxQ - minQ);
}
}
Is it possible to do somthing similar like this?
No, it is impossible in C#. I suggest you learn about Extension Methods and Partial classes.
You can use static classes and singletons as well, but try to avoid the temptation to access it from every part of your project - it will be difficult to modify and refactor it in the future.
You cannot create a global function, but you can create a static method in a static class:
namespace MyNamespace
{
public static class Util
{
public static double GetRandomNumber(..) { ... }
}
}
and use it like
var myNumber = Util.GetRandomNumber(...);
The important part here is that the method is static, which means that you don't need an instance of the class to call it. The static class means that it is impossible to create an instance of that class.

Manipulate sealed type in C#

I want to, for example, add a method to integer (i.e., Int32), which will make me able to do the following:
int myInt = 32;
myInt.HelloWorld();
One can say, instead of insisting doing the above, you can write a method which takes an integer, HelloWorld(integer), like the following, more easily:
int myInt = 32;
HelloWorld(myInt);
However, I'm just curious whether it's possible or not. If true, is that a good programming practice to add some other functionality to well known classes?
PS: I tried to make another class which inherits from Int32, but cannot derive from sealed type 'int'.
You can add an extension method for int32.
public static class Int32Extensions
{
public static void HelloWorld(this int value)
{
// do something
}
}
Just remember to using the namespace the class is in.
I think you mention extension method programming guide of extension method
You're after Extension Methods.
There is nothing wrong with them OOP speaking because you don't have access to private variables nor alter the behaviour of the object in any way.
Its only syntactic sugar on what you've described exactly.
Q: Is that a good programming practice to add some other functionality to well known classes?
This type of discussion really belongs on 'Programmers'.
Please take a look at this discussion on Programmers, that has a lot of philosophical points on using extension methods:
https://softwareengineering.stackexchange.com/questions/77427/why-arent-extension-methods-being-used-more-extensively-in-net-bcl
Also:
https://softwareengineering.stackexchange.com/questions/41740/when-to-use-abstract-classes-instead-of-interfaces-and-extension-methods-in-c?lq=1
Use Extensions methods
static class Program
{
static void Main(string[] args)
{
2.HelloWorld();
}
public static void HelloWorld(this int value)
{
Console.WriteLine(value);
}
}
You may use extension method
like this:
public static class IntExtensions
{
public static string HelloWorld(this int i)
{
return "Hello world";
}
}

Fluent Interface, Need something like global methods in C#

Im currently trying to build a Fluent Interface for a ServiceLocator. To ensure that each the developer can easily setup 1-to-n mappings
I'd like something like this
ServiceLocator.Instance.For<IFoo>(Use<Foo>(), Use<FooBar>());
Singleton is workin fine... the methodsignature for the For method looks like this
public void For<TInterface>(params type[] services)
{
// ...
}
So I was looking for something like a global method
C# has some global methods, all methods which are defined on System.Object. But when I create a new generic ExtensionMethod on System.Object, the method will not be visible.
public static class MyExtensions
{
public static void Use<T>(this Object instance)
{
// ..
}
}
MethodChaining would be the alternative, but this approach looks sexy :D
Has anyone an idea?
Well, actually when I create an extension method for Object, it is visible. As in,
public static class Extensions
{
public static void doStuff<T>(this T myObject)
{
}
}
class Program
{
static void Main(string[] args)
{
int a = 5;
a.doStuff();
string b = "aaa";
b.doStuff();
List<int> c = new List<int>() { 1, 2, 3, 10 };
c.doStuff();
Extensions.doStuff(c);
}
}
Did I misunderstand your question?
You need to add a using statement for the namespace containing your extension method in order for it to be visible. Adding extension methods to object is rarely a good idea.
EDIT:
Okay, now I understand what you're asking. In order to use an extension method you need an instance. You're asking for a static extension method on object (Equals and ReferenceEquals are static methods), and that's not possible. If you define an extension method on object, it will be available on all instances and I'm sure that's not what you want.
public static class ObjectExtensions
{
public static string TypeFullName(this object obj)
{
return obj.GetType().FullName;
}
}
static void Main(string[] args)
{
var obj = new object();
Console.WriteLine(obj.TypeFullName());
var s = "test";
Console.WriteLine(s.TypeFullName());
}
Service Locator is widely considered to be an anti-pattern. Also, a common registration interface is widely considered to be an unsolvable problem unless you are requiring use of a specific container.
Looking past these two questionable decisions, you can remove the need for the global method by defining overloads of For which accept multiple type arguments:
ServiceLocator.Instance.For<IFoo, Foo, FooBar>();
The For methods would look like this:
public void For<TInterface, TImplementation>()
public void For<TInterface, TImplementation1, TImplementation2>()
...
You have to define an overload for each type count, but it requires the minimal syntax and maximum amount of discoverability. For reference, the .NET Framework's Action and Func types support 9 type arguments.
After writing this out, though, I wonder if I misunderstood the question: why would you specify multiple implementations for the same interface? Wouldn't that lead to ambiguity when resolving IFoo?

Is it possible to write a extension method for an abstract class

Why I'm unable to extend an abstract class. Is there any work around to achieve this?
In silverlight, Enum.GetNames is missing. So, I would like to extend it and have it in my utility assembly. By then, got into this.
The problem here is not that you can't add an extension method to an abstract class (you can - you can add an extension method to any type) - it's that you can't add a static method to a type with extension methods.
Extension methods are static methods that present themselves in C# as instance methods. But they're still static. Adding a static method to a type requires the ability to redefine the type, which you can only do if you have the source code :)
Best bet, if you want this method, is to write your own static and see if you can perhaps rip the code out of reflector.
However, it's entirely possible that it's not there because it's physically not supported in Silverlight (I don't know - I haven't investigate)
EDIT
Following on from your comment - and I hope that I've understood you here - I think what you want to be able to do is something like this (targetting object to prove the point):
public static class ExtraObjectStatics
{
public static void NewStaticMethod()
{
}
}
public class Test
{
public void foo()
{
//You can't do this - the static method doesn't reside in the type 'object'
object.NewStaticMethod();
//You can, of course, do this
ExtraObjectStatics.NewStaticMethod();
}
}
If you think about it - of course you can't inject new static methods into an existing type because, like I said in paragraph two, you have to be able to recompile the underlying type; and there simply is no way around that.
What you can do is (and I don't actually recommend this - but it's an option) create yourself a new type called Enum and place it inside a new namespace:
namespace MySystem
{
public class Enum
{
public static string[] GetNames()
{
//don't actually know how you're going to implement it :)
}
}
}
And now - when you want to use it, what you can't do is this:
using System;
using MySystem;
namespace MyCode
{
public class TestClass
{
public static void Test()
{
Enum.GetNames(); //error: ambiguous between System and MySystem
}
}
}
Because the using in the outermost scope to both 'System' and 'MySystem' will cause the compiler not to be able to resolve the correct Enum type.
What you can do, however, is this:
using System;
namespace MyCode
{
using MySystem; //move using to inside the namespace
public class TestClass
{
public static void Test()
{
//will now work, and will target the 'MySystem.Enum.GetNames()'
//method.
Enum.GetNames();
}
}
}
Now, code within that namespace (within that file only) will always resolve Enum to the one in your namespace because that's the nearest using directive in terms of scope.
So, you can think of this as overriding the whole Enum type for the benefit of a given namespace that includes a using MySystem; in it.
But, it does exactly that - it replaces the existing System.Enum with MySystem.Enum - meaning that you lose all the members of the System.Enum type.
You could get around this by writing wrapper methods in your Enum type around the System.Enum versions - making sure that you fully-qualify the type as System.Enum.
Having looked at the implementation of the GetNames method in Reflector - it relies on internal data that I don't think you're going to be able to build... but I would be very interested to hear if you are actually able to reproduce the method in Silverlight.
public abstract class Foo
{
public abstract void Bar();
}
public static class FooExtensions
{
// most useless extension method evar
public static void CallBar(this Foo me)
{
me.Bar();
}
}
Sure, no problem.

C# virtual static method

Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world?
I know the concept has already been underlined but I did not find a simple answer to the previous question.
virtual means the method called will be chosen at run-time, depending on the dynamic type of the object. static means no object is necessary to call the method.
How do you propose to do both in the same method?
Eric Lippert has a blog post about this, and as usual with his posts, he covers the subject in great depth:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/calling-static-methods-on-type-parameters-is-illegal-part-one
“virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”
The contradiction between "static" and "virtual" is only a C# problem. If "static" were replaced by "class level", like in many other languages, no one would be blindfolded.
Too bad the choice of words made C# crippled in this respect. It is still possible to call the Type.InvokeMember method to simulate a call to a class level, virtual method. You just have to pass the method name as a string. No compile time check, no strong typing and no control that subclasses implement the method.
Some Delphi beauty:
type
TFormClass = class of TForm;
var
formClass: TFormClass;
myForm: TForm;
begin
...
formClass = GetAnyFormClassYouWouldLike;
myForm = formClass.Create(nil);
myForm.Show;
end
Guys who say that there is no sense in static virtual methods - if you don't understand how this could be possible, it does not mean that it is impossible. There are languages that allow this!! Look at Delphi, for example.
I'm going to be the one who naysays. What you are describing is not technically part of the language. Sorry. But it is possible to simulate it within the language.
Let's consider what you're asking for - you want a collection of methods that aren't attached to any particular object that can all be easily callable and replaceable at run time or compile time.
To me that sounds like what you really want is a singleton object with delegated methods.
Let's put together an example:
public interface ICurrencyWriter {
string Write(int i);
string Write(float f);
}
public class DelegatedCurrencyWriter : ICurrencyWriter {
public DelegatedCurrencyWriter()
{
IntWriter = i => i.ToString();
FloatWriter = f => f.ToString();
}
public string Write(int i) { return IntWriter(i); }
public string Write(float f) { return FloatWriter(f); }
public Func<int, string> IntWriter { get; set; }
public Func<float, string> FloatWriter { get; set; }
}
public class SingletonCurrencyWriter {
public static DelegatedCurrencyWriter Writer {
get {
if (_writer == null)
_writer = new DelegatedCurrencyWriter();
return _writer;
}
}
}
in use:
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400.0
SingletonCurrencyWriter.Writer.FloatWriter = f => String.Format("{0} bucks and {1} little pennies.", (int)f, (int)(f * 100));
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400 bucks and 0 little pennies
Given all this, we now have a singleton class that writes out currency values and I can change the behavior of it. I've basically defined the behavior convention at compile time and can now change the behavior at either compile time (in the constructor) or run time, which is, I believe the effect you're trying to get. If you want inheritance of behavior, you can do that to by implementing back chaining (ie, have the new method call the previous one).
That said, I don't especially recommend the example code above. For one, it isn't thread safe and there really isn't a lot in place to keep life sane. Global dependence on this kind of structure means global instability. This is one of the many ways that changeable behavior was implemented in the dim dark days of C: structs of function pointers, and in this case a single global struct.
Yes it is possible.
The most wanted use case for that is to have factories which can be "overriden"
In order to do this, you will have to rely on generic type parameters using the F-bounded polymorphism.
Example 1
Let's take a factory example:
class A: { public static A Create(int number) { return ... ;} }
class B: A { /* How to override the static Create method to return B? */}
You also want createB to be accessible and returning B objects in the B class. Or you might like A's static functions to be a library that should be extensible by B. Solution:
class A<T> where T: A<T> { public static T Create(int number) { return ...; } }
class B: A<B> { /* no create function */ }
B theb = B.Create(2); // Perfectly fine.
A thea = A.Create(0); // Here as well
Example 2 (advanced):
Let's define a static function to multiply matrices of values.
public abstract class Value<T> where T : Value<T> {
//This method is static but by subclassing T we can use virtual methods.
public static Matrix<T> MultiplyMatrix(Matrix<T> m1, Matrix<T> m2) {
return // Code to multiply two matrices using add and multiply;
}
public abstract T multiply(T other);
public abstract T add(T other);
public abstract T opposed();
public T minus(T other) {
return this.add(other.opposed());
}
}
// Abstract override
public abstract class Number<T> : Value<T> where T: Number<T> {
protected double real;
/// Note: The use of MultiplyMatrix returns a Matrix of Number here.
public Matrix<T> timesVector(List<T> vector) {
return MultiplyMatrix(new Matrix<T>() {this as T}, new Matrix<T>(vector));
}
}
public class ComplexNumber : Number<ComplexNumber> {
protected double imag;
/// Note: The use of MultiplyMatrix returns a Matrix of ComplexNumber here.
}
Now you can also use the static MultiplyMatrix method to return a matrix of complex numbers directly from ComplexNumber
Matrix<ComplexNumber> result = ComplexNumber.MultiplyMatrix(matrix1, matrix2);
While technically it's not possible to define a static virtual method, for all the reasons already pointed out here, you can functionally accomplish what I think you're trying using C# extension methods.
From Microsoft Docs:
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Check out Extension Methods (C# Programming Guide) for more details.
In .NET, virtual method dispatch is (roughly) done by looking at the actual type of an object when the method is called at runtime, and finding the most overriding method from the class's vtable. When calling on a static class, there is no object instance to check, and so no vtable to do the lookup on.
To summarize all the options presented:
This is not a part of C# because in it, static means "not bound to anything at runtime" as it has ever since C (and maybe earlier). static entities are bound to the declaring type (thus are able to access its other static entities), but only at compile time.
This is possible in other languages where a static equivalent (if needed at all) means "bound to a type object at runtime" instead. Examples include Delphi, Python, PHP.
This can be emulated in a number of ways which can be classified as:
Use runtime binding
Static methods with a singleton object or lookalike
Virtual method that returns the same for all instances
Redefined in a derived type to return a different result (constant or derived from static members of the redefining type)
Retrieves the type object from the instance
Use compile-time binding
Use a template that modifies the code for each derived type to access the same-named entities of that type, e.g. with the CRTP
The 2022+ answer, if you are running .Net 7 or above, is that now static virtual members is now supported in interfaces. Technically it's static abstract instead of "static virtual" but the effect is that same. Standard static methods signatures can be defined in an interface and implemented statically.
Here are a few examples on the usage and syntax in .Net 7

Categories