Can method parameters be dynamic in C# - dynamic

In c# 4.0, are dynamic method parameters possible, like in the following code?
public string MakeItQuack(dynamic duck)
{
string quack = duck.Quack();
return quack;
}
I've many cool examples of the dynamic keyword in C# 4.0, but not like above. This question is of course inspired by how python works.

Yes, you can absolutely do that. For the purposes of static overload resolution, it's treated as an object parameter (and called statically). What you do within the method will then be dynamic. For example:
using System;
class Program
{
static void Foo(dynamic duck)
{
duck.Quack(); // Called dynamically
}
static void Foo(Guid ignored)
{
}
static void Main()
{
// Calls Foo(dynamic) statically
Foo("hello");
}
}
The "dynamic is like object" nature means you can't have one overload with just an object parameter and one with just a dynamic parameter.

See documentation http://msdn.microsoft.com/en-us/library/dd264741(VS.100).aspx

Yes, you can do that. As stated in C# 4.0 specification, the grammar is extended to support dynamic wherever a type is expected:
type:
...
dynamic
This includes parameter definitions, of course.

Yes; see e.g.
http://blogs.msdn.com/cburrows/archive/2008/11/14/c-dynamic-part-vi.aspx
or Chris' other blogs. Or grab VS2010 Beta2 and try it out.

Related

How to handle conflicting function names when implementing multiple interfaces?

I have an interface defined in C# that implements IEnumerable. The implementation of the interface will be done in C++/WinRT as it needs direct access to native code. When I attempt to implement this interface using C++/WinRT, the generated header/implementation contains two 'First()' functions (one from IIterable, and one from IBindableIterable) with different return types. Obviously this isn't going to compile.
Is there some way to "rename" one (or both) of the conflicting functions in the IDL file? C++/CX had a work around that allowed you to use a different function name and then 'bind' it back to the interface name.
Simplified example code below:
Interface:
public interface IUInt32Array : IEnumerable<uint> {}
IDL:
[default_interface]
runtimeclass UInt32Array : IUInt32Array
{
UInt32Array(UInt32 size);
}
IDL Generated Header:
struct UInt32Array : UInt32ArrayT<UInt32Array>
{
UInt32Array(uint32_t size);
Windows::Foundation::Collections::IIterator<uint32_t> First(); // <-- Problem
Windows::UI::Xaml::Interop::IBindableIterator First(); // <-- Problem
}
A solution for this specific problem is to use a combination of 'auto' as the declared return type for the First() function implementation, and to return a type with conversion operators for the two different return types.
Here is an example showing how this was solved in the CppWinRT source code. The linked source code is for the base_collections_vector.h header, specifically see the convertible_observable_vector::First() function (replicated below).
auto First() {
struct result {
container_type* container;
operator wfc::IIterator<T>() {
return static_cast<base_type*>(container)->First();
}
operator wfc::IIterator<Windows::Foundation::IInspectable>() {
return make<iterator>(container);
}
};
return result{ this };
}
Notice here that the function itself is defined as returning auto, which allows us to return an intermediate type. This intermediate type then implements conversion operators for converting to the type expected by the caller. This works for this particular problem as the generated CppWinRT source code immediately assigns the result of the call to a value of the expected type, thus immediately causing the invocation of the conversion operators which in turn return the final correct iterator type.
Thanks to Kenny Kerr who pointed me at both the example and a write-up explaining the above.

Pass annotation to a function in Kotlin

How can I pass an annotion instance to a function?
I would like to call the java method AbstractCDI.select(Class<T> type, Annotation... qualifiers). But I don't know how to pass an annotation instance to this method.
Calling the constructor like
cdiInstance.select(MyClass::javaClass, MyAnnotation())
is not allowed and the #Annotation-Syntax cdiInstance.select(MyClass::javaClass, #MyAnnotation) is not allowed as parameter, too. How can I archive this?
When working with CDI you usually also have AnnotationLiteral available or at least you can implement something similar rather easy.
If you want to select a class using your annotation the following should do the trick:
cdiInstance.select(MyClass::class.java, object : AnnotationLiteral<MyAnnotation>() {})
Or you may need to implement your specific AnnotationLiteral-class if you require a specific value. In Java that would work as follows:
class MyAnnotationLiteral extends AnnotationLiteral<MyAnnotation> implements MyAnnotation {
private String value;
public MyAnnotationLiteral(String value) {
this.value = value;
}
#Override
public String[] value() {
return new String[] { value };
}
}
In Kotlin however, you can't implement the annotation and extend AnnotationLiteral or maybe I just did not see how (see also related question: Implement (/inherit/~extend) annotation in Kotlin).
If you rather want to continue using reflection to access the annotation then you should probably rather use the Kotlin reflection way instead:
ClassWithAnno::class.annotations
ClassWithAnno::methodWithAnno.annotations
Calling filter, etc. to get the Annotation you desire or if you know there is only one Annotation there, you can also just call the following (findAnnotation is an extension function on KAnnotatedElement):
ClassWithAnno::class.findAnnotation<MyAnnotation>()
ClassWithAnno::methodWithAnno.findAnnotation<MyAnnotation>()
One could annotate a method or field with the annotation an get it per Reflection:
this.javaClass.getMethod("annotatedMethod").getAnnotation(MyAnnotation::class.java)
Or According to Roland's suggestion the kotlin version of the above:
MyClass::annotatedMethod.findAnnotation<MyAnnotation>()!!
As suggested by Roland for CDI it is better to use AnnotationLiteral (see his post).

Getter setter in C# VS2017

I've been starting to use VS2017 Community. This bugs me:
Below is normal getter setter from previous VS:
public string Name
{
get{ return _name;}
set{ _name = value;}
}
This is the new getter setter:
public string Name { get => _name; set => _name = value; }
Anyone can explain to me why the syntax is changed?
I wouldn't say they changed it, I would say they gave us some new syntax options. You can still use the "old" way of declaring getters and setters, but there is now also a more functional programming style of doing it as well. In C#6 Microsoft already introduced using expressions for getter only properties doing:
public int SomeProp => someMethod();
C#7 enhanced this support allowing it to be used for getters AND setters. One nice feature of this is with the new "throw expressions" feature which allows us to make some concise syntax. For example, before you had to do.
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(Name));
_name = value;
}
}
We can now simplify this to:
private string _name;
public string Name {
get => _name;
set => _name = value ?? throw new ArgumentNullException(nameof(Name));
}
Granted, you could do the throw expression even without making the setter a lambda, but as you can see, for simple things, it makes the syntax very concise.
As with anything, use the syntax that makes the most sense to you and is most readable for the people who will be coding your application. Microsoft has been making a push to add more and more functional programming style features to C# and this is just another example of that. If you find it ugly/confusing/not needed, you can absolutely accomplish everything you need with the existing method. As another example, why do we have while and do while loops? I can honestly say I've used a do while loop maybe 5 times in my career. A while loop can do everything a do while can just with different syntax. However, there are sometimes where you realize that using a do while will make your code more readable, so why not use it if it makes things easier to follow?
The syntax hasn't changed: it has been improved. C# has been always backwards-compatible with syntax and grammar from previous versions.
Why property getters/setters can be implemented with lambda syntax (expression-bodied accessors)? Probably there's no scientific reason to do so, but there's a consensus about introducing useful functional programming constructs in C# as it turns the language into a more productive tool.
Just foillow up C#'s evolution since C# 2.0:
From delegates provided as regular methods to anonymous delegates.
LINQ, lambda-style delegates/expression trees.
Expression-bodied methods.
...and expression-bodied accessors! And probably future C# versions will introduce even more functional programming-style syntax and grammar.
You'll notice they removed the 'return' syntax, this was done (from what I've read) to make it more clear that they aren't functions (and when reflected can't be treated as functions and can't be made into delegates) but rather this kind of 'pseudo-function' (if you get what I'm trying to well get at).
So basically its to make it more clear that the getter is linking this this variable and the repeating for the setter. It also is because in newer versions you can do something like
public int MyInt => x ? y:z;
Which represents
public int MyInt
{
get
{
return x ? y:z;
}
}
Also both syntax should work, its just a new syntax that they added to bring it in line with the above example.
I know I am adding this details after a year, but just understood that my VS 2017 generated new syntax on my web user control, and that does not reflect on the aspx file when I wanted to set a value for it.
like
private bool _ShowBankDetailPanel = false; //To Show Bank details section in registration
public bool ShowBankDetailPanel { get => _ShowBankDetailPanel; set => _ShowBankDetailPanel = value; }
and on ASPX side you will NOT have property like
it is only recognize
old style getter setter....(I experience this,,, but I am be wrong)

In Managed C++, what is the proper way to define a static singleton instance in a class?

Jumping to Visual Studio 2015 from Visual Studio 2013, I've noticed some differences in how static self-instances in managed C++ classes are accepted by the compiler. Consider these two examples:
Method 1:
public ref class CResourceManager
{
public:
static property CResourceManager^ Instance
{
CResourceManager^ get() { return %m_Instance; }
}
private:
static CResourceManager m_Instance;
};
Method 2:
public ref class CResourceManager
{
public:
static property CResourceManager^ Instance
{
CResourceManager^ get() { return m_Instance; }
}
private:
static CResourceManager^ m_Instance = gcnew CResourceManager;
};
Method 1 used to work on 2013, but it's failing to compile on 2015. I unfortunately do not have the exact compiler error handy, but it was one of those "Missing semicolon before variable name" errors, basically saying it couldn't find the type CResourceManager (pointing to the static variable declaration).
So on to my questions:
Is method 1 supposed to work or be valid in managed C++?
Why would the second method work in 2015, but not the first (i.e. what are the differences)?
Which method is the proper way to accomplish the end goal?
Method 2 is the proper way to do it. The code you have listed is the equivalent of the C# idiom.
Method 1 is a bit unusual.
The lack of a ^ on a declaration would normally mean that the variable is not allocated on the managed heap. However, since it's a static class member, I'm not sure where it actually gets created.
% is normally used for declaring tracking references, the equivalent of passing a variable by ref or out in C#. To be honest, I didn't think that applying % to a variable without either ^ or % and taking the result as a ^ was even valid. (Though considering the 2015 compiler rejects it, it may not be.)
Even if Method 1 is valid, I'd still go with Method 2: The storage location of m_Instance and how it's returned are both plain, common, and easy to understand. This beats having to think about how the code works any day.

Type hinting v duck typing

Using the following simple Example (coded in php):
public function doSomething(Registry $registry)
{
$object = $registry->getData('object_key');
if ($object) {
//use the object to do something
}
}
public function doSomething($registry)
{
$object = $registry->getData('object_key');
if ($object) {
//use the object to do something
}
}
What are the benefits of either approach?
Both will ultimately fail just at different points:
The first example will fail if an object not of type Registry is passed, and the second will fail if the object passed does not implement a getData method.
How do you choose when to use either approach?
Those are 2 different design approaches. The responsibility falls on the developer(s) to make sure either methods won't fail.
Type hinting is a more robust approach while duck typing gives you more flexibility.