Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# overloading: method for null value

I am currently writing a serializer for some of my classes. I created a set of static methods with the following signatures

public static string serialize(int val);
public static string serialize(string val);
public static string serialize(float val);
public static string serialize(MyOwnClass val);
public static string serialize(AnotherClass val);
public static string serialize(SomethingElse val);

Additionally, sometimes I have to deal with null values. I would like to treat them in a special way, i.e. a signature like:

public static string serialize(null val);

The call to the function should be something like:

string s = serialize(someVariableThatMightBeNull);

And it should be triggered anytime serialize is called with the value null, independent of which type the variable was declared with.

Is there any way to implement this in C#?

Currently my only solution would be to add this line to each method: (for datatypes that can be null):

if(val == null){ dealWithNull(); }

This solution seems a bit tedious, as I have about 30 different cases and I would prefer not having a dispatch method.


As an example, Xtend features dispatch methods that also offer the Void type which checks for null values. Xtend Dispatch Methods

like image 281
stklik Avatar asked May 21 '26 21:05

stklik


1 Answers

If I understood you correctly :

I'd go with a method signature waiting for an object.

The compiler will ALWAYS choose the method signature that seem the closest to what you used. So it will only use the method with the object signature if no other are available.

In this method, you will be able to check if the parameter is null and/or handle classes that does not have their own static method for serialization


For custom serialization, IMHO, I think it would be better to let each class handle themselves.

In order to do this, I'd define an Interface ICustomSerialization containing a method string CustomSerialization()

I'd then make each one of the classes I'd need to serialize inherit from this interface and implement the the method inside each class.

That would offer the benefit of having the serialization code IN the related class, avoid a massive serialization class.

Allow your serializer to work with interface (and thus not having to know how to handle each particular class)

like image 151
Sidewinder94 Avatar answered May 23 '26 12:05

Sidewinder94



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!