Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I haven't used generics before in my C# programming, but I think I have found a use for them. I just don't know how to go about converting this boilerplate code to a single generic...

In the example code below, the PlayBall method and the variable passed to it (along with the variable's type) are what changes from each time this set of code is run. Sometimes also, the method call takes no arguments either.

Is there a way to convert this to a generic?

Thanks!

C#
lock (slaveLocker)
{
    foreach (KeyValuePair<Tuple<string, string>, ICallbacks> kvp in slaves)
    {
        try
        {
           kvp.Value.PlayBall(ball);
        }
        catch
        {
           slaves.Remove(kvp.Key);
        }
    }
}
Posted
Comments
Sergey Alexandrovich Kryukov 1-Oct-13 10:43am    
What's wrong about just reading the MSDN on the topic?
—SA
johannesnestler 1-Oct-13 16:22pm    
Generics is just a buzzword for a simple thing: use of types as variables. But if I look at your code-sample it's hard to guess - without context - if it could be usefull for your project. But I guess you want the "ball" parameter's type to be generic? If this is just a method - you could use a generic method with the correct constraints (I think you depend on an interface implementation?), but if you have a bunch of methods using the same generic type paramter - you better create a generic type as SA suggested...

1 solution

The question itself is incorrect. You cannot possibly convert this fragment of code to generic. You can add a generic parameters to a type declaration (it will make an incomplete generic type, a complete type should be obtained by instantiation with concrete generic parameters) or to a method declaration.

You already used generic types KeyValuePair and Tuple, now you need to create your own type or method using generics. In a pinch, look at the declarations of the two generic types mentioned above, to see the syntax. And then read on generic declarations in MSDN documentation. This is really, really simple:
http://msdn.microsoft.com/en-us/library/512aeb7t.aspx[^].

As you did not provide a base for turning anything into generics (no type or method declaration), at this moment making up a code sample would be of little help. If you read documentation, it will be a lot easier.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900