C# XNA Xbox, in this case optional parameters are not optional - c#

Apparently optional parameters won't work in C# Xna when used on the Xbox, there non suportedness is stated during compilation.
I have a situation like this:
func(float? a = null, int? b = null)
With large numbers of thease optional parameters that default to the "undefined" value, null. This situation is required.
In the simplified example above this can be unwrapped, although this isn't as optional parameters allow:
func()
func(float? a)
func(int? b)
func(float? a, int? b)
However with large numbers of parameters this isn't practical.
Some combinations of parameters definedness isn't permitted and results in paths through the function where I throw argument exceptions, others result in various different things occurring depending on the values of the parameters. This is similar to polymorphism between functions with the same name but is not the same.
I could alternatively, and probbably most practically, require all the parameters instead.
func(float? a, int? b)
Then call as so:
func(null, 4)
Where the first is undefined.
Instead of using one of the above bodges, is there a way to enable optional parameters in C# XNA on Xbox?

I would use old-fashioned overloads that take different numbers of parameters, and forward the calls on from there, along with the "default" values. Zero code changes to the callers.
If the types are outside your control: extension methods to add the overloads.

I've certainly run on the XBOX with optional parameters, but it required some tweaking of the build settings. From what I recall it will not work with WP7 however.
I think it might have been related to the Language Version being used.
Check out the following links:
http://msdn.microsoft.com/en-us/library/ff827884.aspx
http://forums.create.msdn.com/forums/p/54007/327944.aspx

I don't think you can enable the optional parameters. Maybe you can use an alternative. like the params keyword that creates an array, you could just pass an object as parameter
public class MyParams
{
public float? a {get;set;}
public int? b {get;set;}
}
func(new MyParams { b = 5 });
With that solution, you have all the flexibility you might want. You can add, remove parameters without thinking of adding/removing new overload. And if you remove or edit a parameter, you'll get a compile time error, something you might not get with multiple overload.

Related

Why does .NET List Sort() not take an explicitly declared delegate object?

Quick question.
In the second example on this documentation page (the second code block, featuring a method called CompareDinosByLength), the Sort method is called as such:
dinosaurs.Sort(CompareDinosByLength);
Why is it that the Sort method didn't need an explicitly declared delegate, as I would have thought by reading the Delegate documentation? Before I found that example, I was attempting to do it like so:
delegate int CompareDinosDel(string first, string second);
CompareDinosDel newDel = CompareDinosByLength;
dinosaurs.Sort(newDel);
But I kept getting errors related to the delegate / delegate method not being proper Comparers.
Shouldn't both work?
Why is it that the Sort method didn't need an explicitly declared delegate?
C# permits a method group -- that is, a method which is named without having the (...) argument list to invoke it -- to be used in a context where a delegate is expected. The compiler performs overload resolution on the method group as though the method group had been invoked with arguments of the types of the delegate's formal parameters. This determines which method of the method group should be used to create the delegate.
This overload resolution process can sometimes lead to unusual situations involving method type inference when the method group is undergoing overload resolution to a delegate type which is a formal parameter type of a generic method; Sort, fortunately is not a generic method, so these oddities do not come into play.
This feature was added to C# 2.0; before that a method group had to be converted to a delegate via
new MyDelegate(MyMethod)
I keep getting errors related to the delegate / delegate method not being proper Comparers. Shouldn't both work?
Unfortunately, no. C# does not have structural identity on delegate types. That is:
delegate void Foo();
delegate void Bar();
...
Foo foo = ()=>{};
Bar bar = foo; // ERROR!
Even though Foo and Bar are structurally identical, the compiler disallows the conversion. You can however use the previous trick:
Bar bar = foo.Invoke;
This is equivalent to
Bar bar = new Bar(foo.Invoke);
However the new bar has as its action to invoke foo; it goes through a level of indirection.
This feature does make some sense.
Reason one:
You don't expect structural identity to work in other places:
struct Point { int x; int y; ... }
struct Pair { int key; int value; ... }
....
Point point = whatever;
Pair pair = point; // ERROR
Reason two:
You might want to say:
delegate int PureMethod(int);
And have a convention that PureMethod delegates are "pure" -- that is, the methods they represent do not throw, always return, return a value computed only from their argument, and produce no side effects. It should be an error to say
Func<int, int> f = x => { Console.WriteLine(x); return x+1; };
PureMethod p = f;
Because f is not pure.
However in hindsight people do not actually make semantics-laden delegates. It is a pain point that a value of type Predicate<int> cannot be assigned to a variable of type Func<int, bool> and vice versa.
If we had to do it all over again, I suspect that delegates would have structural identity in the CLR.
Finally, I note that VB is much more forgiving about inter-assigning mixed delegate types; it automatically builds an adapter delegate if it needs to. This can be confusing because sometimes it looks like referential identity is maintained when in fact it is not, but this is in keeping with the VB philosophy of "just make my code work".
dinosaurs.Sort(CompareDinosByLength);
CompareDinosDel newDel = CompareDinosByLength;
dinosaurs.Sort(newDel);
Shouldn't both work?
No, because you are passing two very different things into those two function calls.
The key here is to recognize that, in both cases, what you actually pass into the method is a delegate. In the first case, the compiler is implicitly creating a delegate of the correct type for you, even though you didn't explicitly ask it to. In the second case, you're making your own delegate, but it's the wrong type, so that attempt will fail.
Starting with .NET 2.0, the C# compiler allow you to skip explicitly create delegates in many situations. If you use a method name in a context where a delegate is expected, and the compiler can verify that the method signature and delegate signature match, it will implicitly construct a delegate instance using the method. That is, instead of doing this (the "old" way)
this.SubmitButton.Click += new System.EventHandler(this.SubmitButton_Click);
You can now do this:
this.SubmitButton.Click += this.SubmitButton_Click;
Visual Studio itself will still generate the older syntax, I assume because it still works and because it's not worth the developer's time to go messing around with it for very little benefit. However, most popular code analysis tools will flag the redundant delegate creation if you use it in your own code.
This same technique works anywhere you have a method (technically a "method group", since one method name can refer to more than one overload), and you assign it to a variable of a delegate type. Passing a method as a parameter into another method is the same type of assignment operation: you are "assigning" the actual parameter at the call site to the formal parameter in the method body, so the compiler does the same thing. In other words, the following two method calls do exactly the same thing:
dinosaurs.Sort(CompareDinosByLength);
dinosaurs.Sort(new Comparison<string>(CompareDinosByLength));
Your unsuccessful attempt to make a delegate, on the other hand, did something slightly different:
dinosaurs.Sort(new CompareDinosDel(CompareDinosByLength));
This time, you told the compiler exactly what kind of delegate you wanted, but that's not the kind of delegate that the method expected. In general, the compiler isn't going to try to second guess what you told it do to; if you ask it to do something that looks "fishy", it will produce an error (in this case, a type mismatch error).
This behavior is similar to what would happen if you tried to do this:
public class A
{
public int x;
}
public class B
{
public int x;
}
public void Foo(A a) { }
public void Bar()
{
B b = new B();
this.Foo(b);
}
In this case, A and B are two distinct types, even though their "type signature" is exactly the same. Any line of code that works on an A will also work equally well on a B, but yet, we cannot use them interchangeably. Delegates are types like any other types, and C#'s type safety rules require that we use the correct delegate types where we need them, and can't get away with just using a close enough type.
The reason this is a good thing is because a delegate type may have a lot more meaning that just it's technical components would imply. Like any other data type, when we create delegates for our applications, we usually apply some kind of semantic meaning to those types. We expect, for example, that if we have a ThreadStart delegate, that it's going to be associated with a method that runs when a new thread starts. the delegate's signature is about as simple as you get (no parameters, no return value) but the implication behind the delegate is very important.
Because of that, we generally want the compiler to tell us if we try to use the wrong delegate type in the wrong place. More often than not, that's probably a sign that we are about to do something that may compile, and even run, but is likely to do the wrong thing. That's never something you want from your program.
While all that is true, it's also true that often times you really don't want to assign any semantic meaning to your delegates, or else, the meaning is assigned by some other part of your application. Sometimes you really do just want to pass around an arbitrary piece of code that has to run later. This is very common with functional-style programs or asynchronous programs, where you get things like continuations, callbacks, or user-supplied predicates (look at the various LINQ methods, for example). .NET 3.5 and onward supply a very useful set of completely generic delegates, in the Action and Func family, for this purpose.
Consider the following code:
public class Foo
{
public int Bar { get; set; }
}
public class SomeOtherFoo
{
public int Bar { get; set; }
}
Should I be able to say:
Foo foo = new SomeOtherFoo();
That won't work in C# either. When you have two different types that have the same body/implementation, they are still different types. Two classes with the same properties are still different classes. Two different delegates with the same signature are still different delegates.
The Sort method has already defined the delegate type, and you need to match it. This is very much like it defining a class that it needs to accept as a parameter; you can't just pass in another type with the same properties and methods.
This is what it means for a language to be statically typed. An alternate type system would be to use "Duck Typing" in which the language doesn't apply the constraint that a variable be of a specific type, but rather that it has a specific set of members. In other words, "If it walks like a duck, and quacks like a duck, pretend it's a duck." That is opposed to the style of typing that says, "It must be a duck, period, even if it knows how to walk and quack."

Force generic type parameter

I'm building a HTTP-API wrapper for .NET, which has a bunch of methods to set data in an object, and then it serializes the data and sends it to my server. There are 6 datatypes allowed:
string
int
long
float
double
DateTime
My data attributes use generics:
SetAttribute<T>(string key, T value)
So there is only one generic method to set data. Since I cannot constrain the data types to the 6 mentioned, I use run-time checks and throw an exception when the wrong data type is used.
Now for my problem: I have two versions of SetAttribute, one that takes a single value (of type T) and one that takes multiple values (of type IEnumerable<T>). The problem is that when a programmer uses this wrapper and does not specify the type parameter, the runtime guesses which method to use, for instance:
SetAttribute("testkey","thing,anotherthing,athirdthing".Split(','))
This defaults to the single value method and T is String[] which of course makes my method cast an exception because String[] is not a valid type. If you specify:
SetAttribute<string>("testkey","thing,anotherThing,aThirdThing".Split(','))
The runtime chooses the correct method (multi-value) and no exception is cast because T is then string.
My question: how can I label my methods so that the type parameter is mandatory and must be explicitly defined? Or do I have to detect this at runtime and redirect to the multi-method myself?
Ok, this was originally a comment above since it doesn't necessarily answer your original question but suggests an alternate approach;
I would say using a public generic SetAttribute in this case isn't necessarily a good idea.
Since the types are so constrained, you should probably just write the overloads and move the errors from runtime to compile time. It would also allow you to take IEnumerable<string> etc. with another 6 overloads and eliminate the problem you're having entirely.
You can always implement SetAttribute with a private generic and just call that from each overload, that will remove some duplication.
It will also more or less eliminate the need for runtime checks, since the types are already constrained by the compiler.
Given a parameter type, the compiler finds a best match from your overloads. If you cast your string[] to an IEnumerable<string> you will probably find it works as expected because the best match is a method that has exactly those parameters. But you have no method that takes a string[], so given one as a parameter, the compiler makes the best guess it can.
I would have two separately named methods rather than overloads otherwise it is too easy to run into this problem. Or have 6 separate overloads, as #Joachim suggests.
I would suggest a better solution would be to test whether the value passed in is IEnumerable after it fails everything else and treat it as such if it is. (I imagine that you're handling IEnumerable as a seventh case already).
One solution would be to break your original method into 6 non-generic overloads, and add another generic overload for collections:
void SetAttribute(string key, int value);
void SetAttribute(string key, string value);
// etc
// abd this takes care of collections:
void SetAttribute<T>(string key, IEnumerable<T> value);

Function Parameter type determined at runtime?

Is it in anyway possible ( preferably without using any third party libs), to create a function whose type is determined at runtime in C#?
e.g
public static void myfunc(var x)
{
System.Windows.Forms.MessageBox.Show(x); //just an example
}
NOTE: I want the runtime to determine the type of the parameter and do not want to later cast the parameter to another type, as would be necessary if I use generics. e.g I don't want:
myfunc<T>(T x)
// and then :
MessageBox.Show((string)m);
UPDATE:
I am actually making a function parser for my programming language, which translates to C# code. In my language, I wanted the parameter types to be determined at runtime always. I was looking for some good C# feature for easy translation.
e.g
in my language syntax:
function msg << x
MessageBox.Show x
end
needed to be translated to something that didn't ask for a type at compile time, but would need one at runtime.
e.g
public static void msg(var x)
{
System.Windows.Forms.MessageBox.Show(x);
}
The keyword introduced for runtime binding in C# 4 is dynamic.
public static void myfunc(dynamic x)
This allows you to make assumptions about x that are unchecked at compile time but will fail at runtime if those assumptions prove invalid.
public static void MakeTheDuckQuack(dynamic duck)
{
Console.WriteLine(duck.Quack());
}
The assumption made here is that the parameter will have a method named Quack that accepts no arguments and returns a value that can then be used as the argument to Console.WriteLine. If any of those assumptions are invalid, you will get a runtime failure.
Given classes defined as
class Duck
{
public string Quack()
{
return "Quack!";
}
}
class FakeDuck
{
public string Quack()
{
return "Moo!";
}
}
And method calls
MakeTheDuckQuack(new Duck());
MakeTheDuckQuack(new FakeDuck());
MakeTheDuckQuack(42);
The first two succeed, as runtime binding succeeds, and the third results in an exception, as System.Int32 does not have a method named Quack.
Generally speaking, you would want to avoid this if possible, as you're essentially stipulating that an argument fulfill an interface of some sort without strictly defining it. If you are working in an interop scenario, then perhaps this is what you have to do. If you are working with types that you control, then you would be better served trying to achieve compile time safety via interfaces and/or base classes. You can even use different strategies (such as the Adapter Pattern) to make types you do not control (or cannot change) conform to a given interface.
If you need to know the type... then you need to know the type. You can't have your cake and eat it too.
First off, the cast in your example is unnecessary as all objects implement ToString(). Instead of telling us what you think you need, tell us what problem you are trying to solve. There is almost certainly a solution either via generics or the use of the dynamic keyword (though dynamic is rarely needed), but we need more info. If you add more I'll update this answer.
You could use a type of object or, if you don't know how many items are available, you could use a params object array, i.e. params object[] cParams.

Does the params keyword guarantee items to be in the same order as they are listed?

I'm working on a simple API that will accept a number of IBehaviours which are then applied in configuration. I am designing this using the params keyword since often there is just one behaviour wanted, but sometimes more.
However, it is very important that behaviours are applied in the correct order.
public void Configure(string wow, params IBehaviour[] behaviours) { ... }
Configure("oh yes", new MustHappenFirst(), new MustHappenSecondly());
Does this
Technically imply that behaviours
occurs in the same order when
enumerating? (as in standard-wise,
not simply practically-wise).
Semantically and intuitively convey that same behaviour?
Thanks.
The evaluation of the arguments will happen in left-to-right order and they'll be put into the array in that order.
Note that if "null" is a valid value for a behaviour, you can get into trouble:
Configure("hello", null);
calls
Configure("hello", (IBehaviour[]) null);
not
Configure("hello", new IBehaviour[1] { null } );
so be careful with that.
Yes. When you use params, the compiler just turns the arguments into an array, in the same order that the arguments were listed in the program. They will always be in this order inside the method.
A call to:
Configure("wow", one, two, three);
Will always map to:
Configure("wow", new[] {one, two, three});
Yes. Parameters specified for a method using the params keyword will be placed in the params array in the order they are specified in the method call. This is generally understood to be so by developers, who are familiar with params-using methods like String.Format where the order of a formatting value in the parameter list is very important.
Yes; order is preserved.
Yes; this is fine.

Optional parameters

I've got a method that takes a bunch of optional parameters and I'm overloading the method to supply the different combinations of signatures. Intellisense pops up with a bunch of different signatures but I think it looks quite confusing now because there are different combinations I need to provide, not just building up parameters on the end of the method signature.
Should I just not overload my method and stick to one signature so that the user of my method has to pass in nulls? It would make the signature clearer but makes the calling code look messier.
Are you restricted to using C# 1-3? C# 4 supports optional parameters and named arguments...
Until then, you should probably either stick with overloading or create a separate class with mutable properties, e.g.
FooOptions options = new FooOptions { Name="Jon", Location="Reading" };
Foo foo = new Foo(options);
That can all be done in one statement if you want... and if some of the properties are mandatory, then create a single constructor in FooOptions which takes all of them.
In C# 4 you'd be able to write:
Foo foo = new Foo(name: "Jon", location: "Reading");
if the constructor was written as
public Foo(string name,
int age = 0,
string location = null,
string profession = null)
Named arguments and optional parameters should make it a lot easier to construct immutable types with optional properties in C# 4 :)
Think about params argument of c# method.
void test(params object []arg) {
..
}
You could use the params keyword if the function definitions only vary in length (and not order, otherwise this wont be the best approach).Then in the function you can setup the values you need based on the parameter input

Categories

Resources