Overriding ToString() of List<MyClass> - c#

I have a class MyClass, and I would like to override the method ToString() of instances of List:
class MyClass
{
public string Property1 { get; set; }
public int Property2 { get; set; }
/* ... */
public override string ToString()
{
return Property1.ToString() + "-" + Property2.ToString();
}
}
I would like to have the following:
var list = new List<MyClass>
{
new MyClass { Property1 = "A", Property2 = 1 },
new MyClass { Property1 = "Z", Property2 = 2 },
};
Console.WriteLine(list.ToString()); /* prints: A-1,Z-2 */
Is it possible to do so? Or I would have to subclass List<MyClass> to override the method ToString() in my subclass? Can I solve this problem using extension methods (ie, is it possible to override a method with an extension method)?
Thanks!

Perhaps a bit off-topic, but I use a ToDelimitedString extension method which works for any IEnumerable<T>. You can (optionally) specify the delimiter to use and a delegate to perform a custom string conversion for each element:
// if you've already overridden ToString in your MyClass object...
Console.WriteLine(list.ToDelimitedString());
// if you don't have a custom ToString method in your MyClass object...
Console.WriteLine(list.ToDelimitedString(x => x.Property1 + "-" + x.Property2));
// ...
public static class MyExtensionMethods
{
public static string ToDelimitedString<T>(this IEnumerable<T> source)
{
return source.ToDelimitedString(x => x.ToString(),
CultureInfo.CurrentCulture.TextInfo.ListSeparator);
}
public static string ToDelimitedString<T>(
this IEnumerable<T> source, Func<T, string> converter)
{
return source.ToDelimitedString(converter,
CultureInfo.CurrentCulture.TextInfo.ListSeparator);
}
public static string ToDelimitedString<T>(
this IEnumerable<T> source, string separator)
{
return source.ToDelimitedString(x => x.ToString(), separator);
}
public static string ToDelimitedString<T>(this IEnumerable<T> source,
Func<T, string> converter, string separator)
{
return string.Join(separator, source.Select(converter).ToArray());
}
}

You'll need to subclass to override any method. The point of generics is to say that you want the same behaviour regardless of the type of T. If you want different behaviour for a specific type of T then you are breaking that contract and will need to write your own class:
public class MyTypeList : List<MyClass>
{
public override string ToString()
{
return ...
}
}
Edited to add:
No, you can't override a method by creating an extension, but you could create a new method with a different signature that is specific to this list type:
public static string ExtendedToString(this List<MyClass> list)
{
return ....
}
Used with
List<MyClass> myClassList = new List<MyClass>
string output = myClassList.ExtendedToString();
I still think you're better off subclassing though...

You can actually use a unicode trick to allow you to define an alternate ToString method directly against your generic list.
If you enable hex character input into visual studio then you can create invisible characters by holding down the Alt key, then pressing the following on your numeric keypad + F F F 9 (now release Alt)
So we can create the following function with an invisible character placed next to its name... (yes i know its VB code, but the concept will still work work for C#)
<Extension()> _
Public Function ToString(ByVal source As Generic.List(Of Char)) As String
Return String.Join(separator:="", values:=source.ToArray)
End Function
Now in visual studio, when you access intellisense against your list, you will be able to choose between either the standard ToString or your custom function.
To enable hex character input into visual studio you may need to edit your registry
open HKEY_CURRENT_USER\Control Panel\Input Method
and create a REG_SZ called EnableHexNumpad set this to 1
You will also need to disable the & shortcuts for the File, Edit, Debug, Data menus,
In visual studio, open the tools menu, select customize, then open the commands tab, and using the modify selection button for any menu item that uses either of the ABCDEF charactes for its short cut, by removing the &
Otherwise you will end up opening popup menus, instead of typing hex characters.

If you method must be named ToString you will have to derive a class from List. You can make it a generic:
static class MyList<T> : List<T>
{
public override string ToString()
{
// ...
}
}
In this case, you would have to use MyList instead of List throughout your application if you wish to have your custom conversion.
However, if you can choose a different name for your method, you can use extension methods and achieve the same effect, with almost no modifications to your code:
You can use extension methods to make this more generic:
static class ListExtension
{
public static void ConvertToString<T>(this IEnumerable<T> items)
{
// ...
}
}
You can use it on any instance of IEnumerable<T> just as if it were an ordinary method:
List<MyClass> list = new List<MyClass> { ... };
Console.WriteLine(list.ConvertToString());
int[] array_of_ints = {1,2,3,4,5};
Console.WriteLine(array_of_ints.ConvertToString());

You would have to create your own custom class that inherits from Collection and then overwride the ToString() method of that class specifically.

No its not possible. ToString of TList will give you the string representation of the list object.
Your options are:
Derive from TList and override the .ToString() method as you mentioned. (in this example I wouldn't say its worth doing so)
Create a helper method that converts a TList list to a comma delimited string e.g. extension method (probably best suggestion)
Use a foreach statement at the Console.WriteLine stage.
Hope that helps!

Depending on the exact reason you have for wanting to override List<T>.ToString() to return something specific it might be handy to have a look at custom TypeConverter implementations.
If you simply want a List<T> of specific T to show itself a certain way as a string in locations where TypeConverters are used, like in the debugger or in string.Format("List: {0}", listVariable) type situations, this might be enough.
You might just have seen the result of ToString() being shown somewhere and wanted to change that, without knowing about the existence of TypeConverter and locations where they are used. I believe many/most/all (not sure which?) of the default TypeConverters in the .NET Framework simply use ToString() when converting any type for which they are defined for to a string.

Related

Creating multiple custom comparators for a dictionary based class

I wish in my class to return a list from a dictionary but allow custom sorting using pre-written comparison methods. In my original java code that I'm converting from, I created compare methods using Google Guava Ordering in my class and then had a single method called the following passing in one of the public comparator methods, kind of declared like this:
public List<Word> getWords(Comparator c) { }
I'm trying to recreate this in C# but I can't figure out how. Essentially in the code below you can see there are three versions for each type of sort, and in addition I end up creating two lists for every return value which seems a bit wasteful.
I looked at creating delegates but got a bit lost, then figured I could create an IComparable, but then saw IComparator and then saw Sort method takes a Comparator.
Can somebody point me in the direction of converting this into a single sort 'GetWords' in the best way, allowing clients to call the GetWords retrieving a sorted list from a pre-supplied set of ordering.
public partial class WordTable
{
private Dictionary<string, Word> words;
public WordTable()
{
//for testing
words = new Dictionary<string, Word>();
words.Add("B", new Word("B", WordTypes.Adjective));
words.Add("A", new Word("A", WordTypes.Noun));
words.Add("D", new Word("D", WordTypes.Verb));
}
public List<Word> GetWords()
{
return words.Values.ToList();
}
public List<Word> GetWordsByName()
{
List<Word> list = words.Values.ToList<Word>();
return list.OrderBy(word => word.Name).ToList();
}
public List<Word> GetWordsByType()
{
List<Word> list = words.Values.ToList<Word>();
return list.OrderBy(word => word.Type).ToList();
}
}
I think you are looking for predicates.
Effectively, you want a predefined set of predicates (one for ByName, one for ByType), and you pass this predicate into the GetWords function.
There are two approaches you can use.
IComparer
This is more closely related to your past Java experience.
The official way is to use IComparer<T> (link).
Similar to your Comparator in the Java example, this enables you to create different sorting methods which all implement the IComparer<Word> interface, and then you can dynamically choose your sorting method.
As a simple example:
public class WordNameComparer : IComparer<Word>
{
public int Compare(Word word1, Word word2)
{
return word1.Name.CompareTo(word2.Name);
}
}
And then you can do:
public List<Word> GetWords(IComparer<Word> comparer)
{
return words.Values.OrderBy(x => x, comparer).ToList();
}
Which you can call by doing:
var table = new WordTable();
List<Word> sortedWords = table.GetWords(new WordNameComparer());
And of course you change the sorting logic by passing a different IComparer<Word>.
Func parameters
From experience, this is a much preferred approach due to LINQ's enhanced readability and low implementation cost.
Looking at your last two methods, you should see that the only variable part is the lambda method that you use to order the data. You can of course turn this variably into a method parameter:
public List<Word> GetWordsBy<T>(Func<Word,T> orderByPredicate)
{
return words.Values.OrderBy(orderBy).ToList();
}
Because the OrderBy predicate uses a generic parameter for the selected property (e.g. sorting on a string field? an int field? ...), you have to make this method generic, but you don't need to explicitly use the generic parameter when you call the method. For example:
var sortedWordsByName = table.GetWordsBy(w => w.Name);
var sortedWordsByLength = table.GetWordsBy(w => w.Name.Length);
var sortedWordsByType = table.GetWordsBy(w => w.Type);
Note that if you select a class, not a value type, that you will either still have to create and pass an IComparer<> for this class, or the class itself must implement IComparable<> so it can be sorted the way you want it to be.
You can introduce ascending/descending ordering:
public List<Word> GetWordsBy<T>(Func<Word,T> orderByPredicate, bool sortAscending = true)
{
return sortAscending
? words.Values.OrderBy(orderBy).ToList()
? words.Values.OrderByDescending(orderBy).ToList();
}
Update
I was trying to do it with delegates, but avoiding the caller having to roll their own lambda statement and use predefined ones.
You can simply wrap your method with some predefined options:
public List<Word> GetWordsBy<T>(Func<Word,T> orderByPredicate)
{
return words.Values.OrderBy(orderBy).ToList();
}
public List<Word> GetWordsByName()
{
return GetWordsBy(w => w.Name);
}
This way, your external callers don't need to use the lambda if they don't want to; but you still retain the benefits of having reusable code inside your class.
There are many ways to do this. I prefer creating preset methods for readability's sake, but you could instead have an enum which you then map to the correct Func. Or you could create some static preset lambdas which the external caller can reference. Or... The world is your oyster :-)
I hope this works, or even compiles.
class WordTable
{
public List<Word> GetWords(IComparer<Word> comparer)
{
return words.Values.OrderBy(x => x, comparer).ToList();
}
}
class WordsByNameAndThenTypeComparer : IComparer<Word>
{
public override int Compare(Word x, Word y)
{
int byName = x.Name.CompareTo(y.Name);
return byName != 0 ? byName : x.Type.CompareTo(y.Type);
}
}
Usage:
WordTable wt = new WordTable();
List<Words> words = wt.GetWords(new WordsByNameAndThenTypeComparer());

Can a C# extension method be added to an F# type?

I've got somebody's F# library with a type in it:
module HisModule
type hisType {
a : float;
b : float;
c : float;
}
I'm using it in C#, and I would like to add a "ToString()" method to it, in order to facilitate debugging.
But the following doesn't seem to work:
public static class MyExtensions
{
public static string ToString(this HisModule.hisType h)
{
return String.Format("a={0},b={1},c={2}", h.a, h.b, h.c);
}
}
....
var h = new hisType();
Console.WriteLine(h.ToString()); // prints "HisModule+hisType"
Any ideas why not?
As others have pointed out, the ToString on object will always be a better match than your extension method. You should probably change the signature of your extension method; changing the name is probably the right way to go.
Moreover: you said that the purpose of this thing was to facilitate debugging. Overriding ToString might be the wrong thing to do there; ToString might be used for something other than debugging. I would be inclined to make my own specially-named method whose name clearly reflects the purpose of the method.
If you are creating a new type and want to have special display behaviour in the debugger, the easiest thing to do is to use the Debugger Display Attributes.
If you want to get really fancy to display a complex data structure in an interesting way, consider writing a Debugger Visualizer.
The answer to your question is "yes". Your sample does not succeed, however, because method resolution succeeds when it finds object.ToString(), so the compiler never looks for extension methods. Try it with a different name:
public static class MyExtensions
{
public static string Foo(this HisModule.hisType h)
{
return String.Format("a={0},b={1},c={2}", h.a, h.b, h.c);
}
}
....
var h = new hisType();
Console.WriteLine(h.Foo());
I think you can not do that, as ToString() is always there, in any object of CLR world.
Check out Eric Lippert answer.
You could create a wrapper type (with an implicit conversion) that overrides ToString.
class MyType {
private readonly hisType _hisType;
private MyType(hisType hisType) {
_hisType = hisType;
}
public static implicit operator MyType(hisType hisType) {
return new MyType(hisType);
}
public override string ToString() {
return String.Format("a={0},b={1},c={2}", _hisType.a, _hisType.b, _hisType.c);
}
}
hisType y;
MyType x = y;

How to create an extension method for ToString?

I have tried this:
public static class ListHelper
{
public static string ToString<T>(this IList<String> list)
{
return string.Join(", ", list.ToArray());
}
public static string ToString<T>(this String[] array)
{
return string.Join(", ", array);
}
}
But it does not work, both for string[] and List<string>. Maybe I need some special annotations?
Extension methods are only checked if there are no applicable candidate methods that match. In the case of a call to ToString() there will always be an applicable candidate method, namely, the ToString() on object. The purpose of extension methods is to extend the set of methods available on a type, not to override existing methods; that's why they're called "extension methods". If you want to override an existing method then you'll have to make an overriding method.
It sounds like you want to replace what files.ToString() returns. You will not be able to do that without writing a custom class to assign files as (i.e. inherit from List and override ToString().)
First, get rid of the generic type (<T>), you're not using it. Next, you will need to rename the extension method because calling files.ToString()will just call the List's ToString method.
This does what you're looking for.
static class Program
{
static void Main()
{
var list = new List<string> { {"a"}, {"b"}, {"c"} };
string str = list.ToStringExtended();
}
}
public static class ListHelper
{
public static string ToStringExtended(this IList<String> list)
{
return string.Join(", ", list.ToArray());
}
}
Simply you Shouldn't use the name ToString for the Extension method as it will never be called because that method already exist and you shouldn't use T as its useless there.
For example i tried this and again it returned same thing:
Console.WriteLine(lst.ToString<int>());
output:
shekhar, shekhar, shekhar, shekhar
so this time i used int and it still ran because that T has no use other then changing the Method Prototype.
So simply why are you using ToString Literal as Method name, as it already exist and you can't override it in a Extension method, this is the reason you had to use that T to make it generic. Use some different name like
public static string ToMyString(this IList<String> list)
That way you wouldn't have to use generic as it useless there and you could simply call it as always.
That said your code is working for me. here is what i tried (in LINQPAD):
void Main()
{
List<string> lst = new List<string>();
lst.Add("shekhar");
lst.Add("shekhar");
lst.Add("shekhar");
lst.Add("shekhar");
lst.ToString<string>().Dump();
}
public static class ListHelper
{
public static string ToString<T>(this IList<String> list)
{
return string.Join(", ", list.ToArray());
}
public static string ToString<T>(this String[] array)
{
return string.Join(", ", array);
}
}
And the output was shekhar, shekhar, shekhar, shekhar
Since you have specified that T in ToString<T> you will need to mention a Type like string or int while calling the ToString method.

How do I override ToString() and implement generic?

I have code that I want to make the following changes:
How do I override ToString()? It says: A static member ...ToString(System.Collections.Generic.List)' cannot be marked as override, virtual, or abstract.
How do I make it generic?
public static override string ToString(this List<int> list) {
string output = "";
list.ForEach(item => output += item.ToString() + "," );
return output;
}
Thanks!
You cannot use extension methods to override an existing method.
From the spec http://msdn.microsoft.com/en-us/library/bb383977.aspx
"You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself."
If you want to override ToString(), you would need to inherit from List<T> rather than try to extend it. You have already seen that you cannot mark the static extension method as override, and overload resolution will always go for the member method over an extension method if it is available. Your options are
Inherit and override
Change your extension method's name to something else ToSpecialString()
Call the method directly using the class name MyExtensions.ToString(myList);
What are you trying to achieve? Often I want to output the contents of a list, so I created the following extension method:
public static string Join(this IEnumerable<string> strings, string seperator)
{
return string.Join(seperator, strings.ToArray());
}
It is then consumed like this
var output = list.Select(a.ToString()).Join(",");
EDIT: To make it easier to use for non string lists, here is another variation of above
public static String Join<T>(this IEnumerable<T> enumerable, string seperator)
{
var nullRepresentation = "";
var enumerableAsStrings = enumerable.Select(a => a == null ? nullRepresentation : a.ToString()).ToArray();
return string.Join(seperator, enumerableAsStrings);
}
public static String Join<T>(this IEnumerable<T> enumerable)
{
return enumerable.Join(",");
}
Now you can consume it like this
int[] list = {1,2,3,4};
Console.WriteLine(list.Join()); // 1,2,3,4
Console.WriteLine(list.Join(", ")); // 1, 2, 3, 4
Console.WriteLine(list.Select(a=>a+".0").Join()); // 1.0, 2.0, 3.0, 4.0
You can only override a method if you inherit the base class.
What I would advocate is calling your extension method .ToCsv().

Partial generic type inference possible in C#?

I am working on rewriting my fluent interface for my IoC class library, and when I refactored some code in order to share some common functionality through a base class, I hit upon a snag.
Note: This is something I want to do, not something I have to do. If I have to make do with a different syntax, I will, but if anyone has an idea on how to make my code compile the way I want it, it would be most welcome.
I want some extension methods to be available for a specific base-class, and these methods should be generic, with one generic type, related to an argument to the method, but the methods should also return a specific type related to the particular descendant they're invoked upon.
Better with a code example than the above description methinks.
Here's a simple and complete example of what doesn't work:
using System;
namespace ConsoleApplication16
{
public class ParameterizedRegistrationBase { }
public class ConcreteTypeRegistration : ParameterizedRegistrationBase
{
public void SomethingConcrete() { }
}
public class DelegateRegistration : ParameterizedRegistrationBase
{
public void SomethingDelegated() { }
}
public static class Extensions
{
public static ParameterizedRegistrationBase Parameter<T>(
this ParameterizedRegistrationBase p, string name, T value)
{
return p;
}
}
class Program
{
static void Main(string[] args)
{
ConcreteTypeRegistration ct = new ConcreteTypeRegistration();
ct
.Parameter<int>("age", 20)
.SomethingConcrete(); // <-- this is not available
DelegateRegistration del = new DelegateRegistration();
del
.Parameter<int>("age", 20)
.SomethingDelegated(); // <-- neither is this
}
}
}
If you compile this, you'll get:
'ConsoleApplication16.ParameterizedRegistrationBase' does not contain a definition for 'SomethingConcrete' and no extension method 'SomethingConcrete'...
'ConsoleApplication16.ParameterizedRegistrationBase' does not contain a definition for 'SomethingDelegated' and no extension method 'SomethingDelegated'...
What I want is for the extension method (Parameter<T>) to be able to be invoked on both ConcreteTypeRegistration and DelegateRegistration, and in both cases the return type should match the type the extension was invoked on.
The problem is as follows:
I would like to write:
ct.Parameter<string>("name", "Lasse")
^------^
notice only one generic argument
but also that Parameter<T> returns an object of the same type it was invoked on, which means:
ct.Parameter<string>("name", "Lasse").SomethingConcrete();
^ ^-------+-------^
| |
+---------------------------------------------+
.SomethingConcrete comes from the object in "ct"
which in this case is of type ConcreteTypeRegistration
Is there any way I can trick the compiler into making this leap for me?
If I add two generic type arguments to the Parameter method, type inference forces me to either provide both, or none, which means this:
public static TReg Parameter<TReg, T>(
this TReg p, string name, T value)
where TReg : ParameterizedRegistrationBase
gives me this:
Using the generic method 'ConsoleApplication16.Extensions.Parameter<TReg,T>(TReg, string, T)' requires 2 type arguments
Using the generic method 'ConsoleApplication16.Extensions.Parameter<TReg,T>(TReg, string, T)' requires 2 type arguments
Which is just as bad.
I can easily restructure the classes, or even make the methods non-extension-methods by introducing them into the hierarchy, but my question is if I can avoid having to duplicate the methods for the two descendants, and in some way declare them only once, for the base class.
Let me rephrase that. Is there a way to change the classes in the first code example above, so that the syntax in the Main-method can be kept, without duplicating the methods in question?
The code will have to be compatible with both C# 3.0 and 4.0.
Edit: The reason I'd rather not leave both generic type arguments to inference is that for some services, I want to specify a parameter value for a constructor parameter that is of one type, but pass in a value that is a descendant. For the moment, matching of specified argument values and the correct constructor to call is done using both the name and the type of the argument.
Let me give an example:
ServiceContainerBuilder.Register<ISomeService>(r => r
.From(f => f.ConcreteType<FileService>(ct => ct
.Parameter<Stream>("source", new FileStream(...)))));
^--+---^ ^---+----^
| |
| +- has to be a descendant of Stream
|
+- has to match constructor of FileService
If I leave both to type inference, the parameter type will be FileStream, not Stream.
I wanted to create an extension method that could enumerate over a list of things, and return a list of those things that were of a certain type. It would look like this:
listOfFruits.ThatAre<Banana>().Where(banana => banana.Peel != Color.Black) ...
Sadly, this is not possible. The proposed signature for this extension method would have looked like:
public static IEnumerable<TResult> ThatAre<TSource, TResult>
(this IEnumerable<TSource> source) where TResult : TSource
... and the call to ThatAre<> fails because both type arguments need to be specified, even though TSource may be inferred from the usage.
Following the advice in other answers, I created two functions: one which captures the source, and another which allows callers to express the result:
public static ThatAreWrapper<TSource> That<TSource>
(this IEnumerable<TSource> source)
{
return new ThatAreWrapper<TSource>(source);
}
public class ThatAreWrapper<TSource>
{
private readonly IEnumerable<TSource> SourceCollection;
public ThatAreWrapper(IEnumerable<TSource> source)
{
SourceCollection = source;
}
public IEnumerable<TResult> Are<TResult>() where TResult : TSource
{
foreach (var sourceItem in SourceCollection)
if (sourceItem is TResult) yield return (TResult)sourceItem;
}
}
}
This results in the following calling code:
listOfFruits.That().Are<Banana>().Where(banana => banana.Peel != Color.Black) ...
... which isn't bad.
Notice that because of the generic type constraints, the following code:
listOfFruits.That().Are<Truck>().Where(truck => truck.Horn.IsBroken) ...
will fail to compile at the Are() step, since Trucks are not Fruits. This beats the provided .OfType<> function:
listOfFruits.OfType<Truck>().Where(truck => truck.Horn.IsBroken) ...
This compiles, but always yields zero results and indeed doesn't make any sense to try. It's much nicer to let the compiler help you spot these things.
If you have only two specific types of registration (which seems to be the case in your question), you could simply implement two extension methods:
public static DelegateRegistration Parameter<T>(
this DelegateRegistration p, string name, T value);
public static ConcreteTypeRegistration Parameter<T>(
this ConcreteTypeRegistration p, string name, T value);
Then you wouldn't need to specify the type argument, so the type inference would work in the example you mentioned. Note that you can implement both of the extension methods just by delegation to a single generic extension method with two type parameters (the one in your question).
In general, C# doesn't support anything like o.Foo<int, ?>(..) to infer only the second type parameter (it would be nice feature - F# has it and it's quite useful :-)). You could probably implement a workaround that would allow you to write this (basically, by separating the call into two method calls, to get two places where the type inferrence can be applied):
FooTrick<int>().Apply(); // where Apply is a generic method
Here is a pseudo-code to demonstrate the structure:
// in the original object
FooImmediateWrapper<T> FooTrick<T>() {
return new FooImmediateWrapper<T> { InvokeOn = this; }
}
// in the FooImmediateWrapper<T> class
(...) Apply<R>(arguments) {
this.InvokeOn.Foo<T, R>(arguments);
}
Why don't you specify zero type parameters? Both can be inferred in your sample. If this is not an acceptable solution for you, I'm frequently encountering this problem too and there's no easy way to solve the problem "infer only one type parameter". So I'll go with the duplicate methods.
What about the following:
Use the definition you provide:
public static TReg Parameter<TReg, T>(
this TReg p, string name, T value)
where TReg : ParameterizedRegistrationBase
Then cast the parameter so the inference engine gets the right type:
ServiceContainerBuilder.Register<ISomeService>(r => r
.From(f => f.ConcreteType<FileService>(ct => ct
.Parameter("source", (Stream)new FileStream(...)))));
I think you need to split the two type parameters between two different expressions; make the explicit one be part of the type of a parameter to the extension method, so inference can then pick it up.
Suppose you declared a wrapper class:
public class TypedValue<TValue>
{
public TypedValue(TValue value)
{
Value = value;
}
public TValue Value { get; private set; }
}
Then your extension method as:
public static class Extensions
{
public static TReg Parameter<TValue, TReg>(
this TReg p, string name, TypedValue<TValue> value)
where TReg : ParameterizedRegistrationBase
{
// can get at value.Value
return p;
}
}
Plus a simpler overload (the above could in fact call this one):
public static class Extensions
{
public static TReg Parameter<TValue, TReg>(
this TReg p, string name, TValue value)
where TReg : ParameterizedRegistrationBase
{
return p;
}
}
Now in the simple case where you are happy to infer the parameter value type:
ct.Parameter("name", "Lasse")
But in the case where you need to explicitly state the type, you can do so:
ct.Parameter("list", new TypedValue<IEnumerable<int>>(new List<int>()))
Looks ugly, but hopefully rarer than the simple fully-inferred kind.
Note that you could just have the no-wrapper overload and write:
ct.Parameter("list", (IEnumerable<int>)(new List<int>()))
But that of course has the disadvantage of failing at runtime if you get something wrong. Unfortunately away from my C# compiler right now, so apologies if this is way off.
I would used the solution:
public class JsonDictionary
{
public static readonly Key<int> Foo = new Key<int> { Name = "FOO" };
public static readonly Key<string> Bar = new Key<string> { Name = "BAR" };
IDictionary<string, object> _data;
public JsonDictionary()
{
_data = new Dictionary<string, object>();
}
public void Set<T>(Key<T> key, T obj)
{
_data[key.Name] = obj;
}
public T Get<T>(Key<T> key)
{
return (T)_data[key.Name];
}
public class Key<T>
{
public string Name { get; init; }
}
}
See:
C#: Exposing type safe API over heterogeneous dictionary

Categories