Archive

Posts Tagged ‘C#’

Suggestion: on Duck Typing and C#/.NET

My comment at:

http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/4272089-support-implicit-interfaces-for-code-reuse

It would be nice indeed if one could define at the client object’s side a static interface that is a subset of the methods of a server (or serving if you prefer) object (it is only the view of the server that the client has gained knowledge of) that has been passed on to the client

Then there could be a service (a facility I mean) that accepts the server object instance and the interface the client has defined (the duck type) and case the server object to that interface by CHECKING that the duck interface is indeed a subset of the methods the server object implements

the check if our duck interface is indeed covered by what the object to be duck-typed offers can be implemented via reflection already

the implementation could be hacked by spitting out a new object (bytecode generation) that wraps each property/method of the object to be duck-typed and calls into the original object, but it would be much better if there was support in the compiler for that (viewing an object via an interface that is compatible to it in functionality, not in strong typing concept)

…when I say support in the compiler, I mean to avoid the proxying layer (of course security should also be considered carefully when implementing such a thing, in case there are pitfalls)

 

A very interesting article on the subject showing how to do DuckTyping in .NET is:

http://www.codeproject.com/Articles/122827/DynamicObjects-Duck-Typing-in-NET

 

Not sure if in the time that has passed (5 years) there have been any DuckTyping-specific additions at C#/.NET

Suggestion: Add support for constants in C# (and VB.net etc.) interfaces

It is rather unfortunate that C# doesn’t support constants in interfaces, whereas Java does.

If IL (intermediate language) that C# usually compiles to (when not using AOT that is like in .NET Native or Xamarin iOS) doesn’t support this, then the compiler could create a special sealed class to carry the constants.

Then, wherever they’re used via the interface it could get them via that class. This would happen internally without the programmer noticing. The programmer should be able to access the constants using:

ISomeInterface.SomeConstant

SomeClass.SomeConstant, where SomeClass implements ISomeInterface

just SomeConstant when the code is inside the body of SomeClass that implements the ISomeInterface

just SomeConstant when there is a “using static” statement (that newer C# has introduced) like “using static ISomeInteface” or “using static ISomeClass”

image

You can vote up this suggestion at:
http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/10724265-add-support-for-constants-in-c-and-vb-net-etc

Suggestion: Introduce .= operator for C#

It would be nice if one could write in C# (and maybe in other .NET languages too):

s = s.SomeMethodOfS(…)…

as

s .= SomeMethodOfS(…)…

that is to have a .= operator, similar to += and other shorthand experession operators

see screenshot for an example usecase from the opensource project FoscamController

image

Ideally, usage of such operators should lead to compiling – whether is is via JIT (Just in Time) or AOT (Ahead of Time) compilation – into more optimized native code, but I’m not sure if C# compilers are exploting that optimization opportunity.

You can vote up this suggestion at:
http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/10724280-introduce-operator-for-c

Suggestion: Define once and reuse result type of method inside its body

It would be nice if one could rewrite this C# snippet:

public SortedDictionary<string, UObject> GetObjects()
{
SortedDictionary<string, UObject> result = new SortedDictionary<string, UObject>();
using (ReadTransaction xact = namingSchema.ReadTransaction())
foreach (ObjectName.RowType row in ObjectName.object_name_(xact))
result.Add(row.name_, row.object_);
return result;
}

 

in a more concise form like:

 

public T GetObjects() where T=SortedDictionary<string, UObject>
{
T result = new T();
using (ReadTransaction xact = namingSchema.ReadTransaction())
foreach (ObjectName.RowType row in ObjectName.object_name_(xact))
result.Add(row.name_, row.object_);
return result;
}

 

In case you wonder what this code is doing, it is getting Ubisense objects and their names, for the whole sample see http://UbisensePositioning.codeplex.com

You can vote on this suggestion at:

http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/10724304-define-once-and-reuse-result-type-of-method-inside

Suggestion: Allow local nested methods inside any code block

It would be nice if one could define methods inside other methods so that they are only accessible in the context of the parent method. In Pascal one could define them at the start of the parent method, before any other commands, but after local variables block, so they could also access the variables of their parent proc.

A trick to implement them could be to make them anononymous methods and assign them to respective local delegates inside the parent method. That way one could also do arbitrary level of such nesting.

Ideally they would also accept an optional inline keyword so that the compiler can inline them (useful for short methods) inside the parent method body (that is the only one allowed to call them anyway [they’re not visible from outside classes or other codeblock in the same class]).

For example, when I refactor code to split a big method to call into other smaller methods, I want them sometimes only to be callable from that original method, and not be accidentally called from elsewhere in my code, including elsewhere in the same class.

Note that in Object Pascal/Delphi such nested methods/procedures/functions could access variables defined at the parent method/procedure/function, since you define them always at the top before the local code.

Implementing the inner methods like you do with anonymous methods allows to grab such local context I believe, so you could allow such inner methods to be defined anywhere inside code blocks to allow access to the variables defined above them in the current code block.

Example syntax suggested:

public void SomeMethod(int i)

{

  if(i>10)

{

    int y = 2;

    void increment(int x) { i = i+x+y; }

    increment(5);

  }

  doSomething( i );

}

 

image

In this screenshot from my enhanced version of Hotspotizer (currently adding speech recognition to that Kinect-based full-body-gestures automation app), I’d like InitSpeechRecognition to only be callable from inside LoadSpeechRecognitionPlugin. I use two methods there to split a bigger method, but I don’t want the 2nd one to be accidentally called from elsewhere in my code.

If you like this suggestion, please vote for it at:
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9639582-allow-nested-methods-inside-any-code-block

Update:

  • Visual Studio Team commented:

You can do this today:

“`
public void SomeMethod(int i)
{
if (i > 10)
{
int y = 2;
Action<int> increment = x => { i += x + y; };
increment(5);
}
doSomething(i);
}
“`

It’s not the syntax you suggested, but it does do the same thing.

Bertrand Le Roy – .NET – Program Manager

 

  • And this is my reply:

Thanks for the pointer Bertrand, having worked with Object Pascal / Delphi for many years too I like its cleaner syntax on this one

Suggestion: Define scoped variable at C# switch conditional statement

Trying to reuse the conditional value of a switch statment in C# at the fallback “default” code block of it, and looking up if that was supported in C#, I found a related discussion at:
http://stackoverflow.com/questions/29628507/c-sharp-get-switch-value-if-in-default-case

I added a comment there and also elaborated it a bit more at a suggestion (PLEASE VOTE IT UP IF YOU AGREE) to Microsoft’s Visual Studio team for the C# language:
https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9578766-define-variable-in-switch

Wouldn’t it be nicer if you could do the following so that fooResult is only visible in the scope of the switch block and then be able to use it at the "default" (fallback case) subblock of the switch code block?

switch (var fooResult = MyFoo()) //SUGGESTION FOR FUTURE C# SYNTAX
{
  case 0: 
    …
    break; 
  …
  default:
    handleOthersCase(fooResult);
    break; 
}

The alternative of evaluating a 2nd time the value inside the "default" is not optimal and the other alternative of defining a local variable outside of the switch block is also not optimal for garbage collection, code optimization, is prone to code errors by accidentally using that value later on after the switch block instead of using some other variable (mistyping the name) etc. It is better practice to allow one to limit the scope of such variables to only where they’re used

a workaround for protecting the local variable from accidental use later on in a long method is to do

{
  var fooResult = MyFoo();
  switch (fooResult)
  {
    case 0:
      …
      break; 
    …
    default:
      handleOthersCase(fooResult);
      break;

  }
}

that is add an extra {…} outside the var and the switch statements, but it doesn’t look pretty

Suggestion: property and event setting block attached to C# type instance

Instead of having to write in C#

      speechRecognizer = CreateSpeechRecognizer();
      if (speechRecognizer != null)
      {
        speechRecognizer.SomeProperty = someValue;
        speechRecognizer.SomeOtherProperty = someOtherValue;
        speechRecognizer.SpeechRecognized += SpeechRecognized;
        speechRecognizer.SpeechHypothesized += SpeechHypothesized;
        speechRecognizer.SpeechRecognitionRejected += SpeechRecognitionRejected;
      }

I’d prefer to write:

      speechRecognizer = CreateSpeechRecognizer() {
        SomeProperty = someValue,
        SomeOtherProperty = someOtherValue,
        SpeechRecognized += SpeechRecognized,
        SpeechHypothesized += SpeechHypothesized,
        SpeechRecognitionRejected += SpeechRecognitionRejected
      }

that is after any Type I’d like to be able to add {…} block with assignments to its properties, like I can do when I create a new type.

Do note that I also would like this syntax and the existing new Type(…) {…} syntax (which is a subset of this one) to support assignment and removal of event handlers, not just setting of properties, as shown in the example above

If you like this suggestion, vote it up at:

http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9479250-property-and-event-setting-block-attached-to-c-ty

Suggestion: implement ignore keyword or allow missing catch block in C#

This is a suggestion I’ve just sent in via Visual Studio’s “Send a frown” feature (rewritten here a bit differently from memory, since that feedback channel doesn’t allow you to access your previous feedback as the Microsoft Connect or the Uservoice site does) :

Instead of having to write

try
{

}
catch (SomeExceptions)
{
//NOP (ignored)
}

I’d like to be able to write

try
{

}
ignore (SomeExceptions);

and similarly if a finally block is used, allow:

try { … }

ignore(SomeExceptions)

finally { … };

That is, I suggest adding an “ignore” keyword, introduced to C# in order to ignore specific exceptions.

Alternatively, could allow a missing catch block, so that the catch (…) clause would be able to be followed directly by a “;” to end the try/catch statement, or by a “finally” clause and its code (sub)block.

try
{

}
catch (SomeExceptions);

and when finally block is used:

try {…}

catch(SomeExceptions)

finally { … }

I’ve also uploaded this for voting up here:
http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/9453432-implement-ignore-keyword-or-allow-missing-catch-bl

Suggestion: Allow new in C# without giving Type

This is a suggestion I’ve just sent in via Visual Studio’s “Send a frown” feature:

Instead of writing statements like:

List<CultureInfo> result = new List<CultureInfo>();

in C# I’d prefer to be able to write

List<CultureInfo> result = new ();

inside the () one would be able to pass contructor parameters and also they should be able to use

SomeClass v = new (someParam) { someProperty = …, otherProperty = … };

syntax, that is be able to initialize properties of the class

What I mean is that I want to omit the type name after the new, since it is deduced from the type I have given to the new var.

Doing

Type v = new (…){…};

is more general from the alternative of doing

  var v = new Type(…){…};

since you would be also able to even do

  someCollectionType.Add(new (…){…});

to add a new member to a typed collection

and also would be able to do

SomeMethod(new (…){…})

where the Type would be deduced from the param of the method (obviously if it is not overloaded with more versions with just 1 param)

Update:

In fact, now that I think of it again, the concept of anonymous types in C# could be merged with the suggested one, making the (…) optional if no constructor parameters are to be used (in anonymous types you only give the {…} part with the properties’ initialization).

The compiler would then resort to making a new anonymous type only if it can’t deduce a type from the usage context.

Of course if the (…) part (constructor parameters) are given, it would never try to make an anonymous type if it can’t find a matching type to instantiate with the respective constructor signature to call.

Have uploaded this for voting up at:

http://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/9453546-allow-new-in-c-without-giving-type

Gotcha: no prefix increment/decrement VB.net operators, but get parsed

In C/C++ and C# one has useful prefix (++index) and postfix (index++) increment operators and corresponding decrement ones.

Although they have a single operant, they’re not working like functions as single + or – prefix would do, but instead they cause side-effects – they edit the variable passed to them. The prefix increment operator first increases a variable’s value, then returns it as result, while the postfix one first returns a variable’s value, then increases it.

Visual Basic.net doesn’t have such operators (and they don’t seem to plan to add such from their response on related feedback at Microsoft Connect.

However, if you type-in

Dim x = ++y

the compiler won’t complain. In fact, it won’t complain even if you type

Dim x = +++++y

The reason is because it thinks this last crazy-looking expression is:

Dim x = +(+(+(+(+y))))

Similarly, it accepts expressions like

Dim x = –y

and

Dim x = —–y

So a programmer coming from C# or converting C# code to VB.net has to be extra careful when converting ++index expressions to use their own implementation as a function that takes a ByRef parameter

%d bloggers like this: