Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

Commented Unassigned: Passing null to overloaded methods. [72]

0
0
Hi, I'm having another issue with passing null to overloaded methods. Here's code sample.
```

public class SimpleObject
{
public string Name { get; set; }
public string GetName()
{
return null;
}
}

public static class LogWriter
{
public static void WriteLine(string message)
{
Console.WriteLine(message);
}

public static void WriteLine(Exception e)
{
if (e == null) Console.WriteLine(string.Empty);
else Console.WriteLine(string.Format("Exception: {0}\n{1}", e.Message, e.StackTrace));
}
}

```
Exposing "SimpleObject" and "LogWriter"
```
Engine.AddHostObject("SimpleObject", new SimpleObject());
Engine.AddHostType("Logger", typeof(LogWriter));
```
Then I will get error by scripting "Logger.WriteLine(SimpleObject.Name)" or "Logger.WriteLine(SimpleObject.GetName())".

The call is ambiguous between the following methods or properties:
'ConsoleApplication1.LogWriter.WriteLine(string)' and 'ConsoleApplication1.LogWr
iter.WriteLine(System.Exception)'

Is that missing converting the value of the property/return value of the method to property type/method return type? In this case, it should be (string)null.

Thank you!
Comments: Ah, you found one of ClearScript's dark corners :) ​ >Is that missing converting the value of the property/return value of the method to property type/method return type? ​ Not exactly. It's simply that `null`'s runtime type is ambiguous. C# can use static typing to select the correct `WriteLine` overload, but that's not an option here. Note that this isn't unique to `null`. Any managed object can match a parameter of the same type, one of its base types, or one of its interfaces. ClearScript normally deals with this by packaging return values with their declared types when they're different from their runtime types. The problem is that ClearScript does __not__ do this for `null`, and that's by design. The reason is that doing so would make `null` results [_truthy_](http://www.codeproject.com/Articles/713894/Truthy-Vs-Falsy-Values-in-JavaScript) and not easily recognizable on the JavaScript side. We'll take another look at this issue; thanks for reporting it. In the meantime, it's not elegant, but you can use a _host variable_ to invoke the correct method: ``` C# engine.AddHostObject("host", new HostFunctions()); engine.AddHostType("CLRString", typeof(string)); // don't hide JS String engine.Execute(@" Logger.WriteLine(host.newVar(CLRString, SimpleObject.Name)) "); ``` Good luck!

Viewing all articles
Browse latest Browse all 2297