Functions in a namespace? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why C# is not allowing non-member functions like C++
Instead of writing StaticClass.Function() I'd like to simply write Function(). There will be many functions and all should be accessible from different (and unrelated) classes and files. How do I put these functions in a specific namespace? Simply declaring it there will give me a compile error
error CS1518: Expected class, delegate, enum, interface, or struct
I know other .NET languages can do it. Is there a compile option i may use? Perhaps even undocumented?

C# does not allow for free functons. Each function must reside in a type. This is just the way it works, it's not a matter of technical possibility, it was a design decision.
You may be interested in this article.
On a side note, ever notice how Intellisense works much, much better when writing C# than C++? This is one of those things that help (not the only one, but one).
EDIT: Funny, in reading that linked article I noticed that this is a dup...

C# does not allow this, by design.
However, if your goal is merely to reduce typing, you have a couple of options.
First, you can use the using Directive to simplify this. By adding this:
using SC = YourNamespace.StaticClass;
You can shorten the calls within that specific document to:
SC.Function();
Another option which is occasionally appropriate would be to use an
Extension method. This can eliminate the need to specify the type, as the function appears to be a member function of the first argument. Of course, this wouldn't work for the supplied example (as it requires a parameter), but is potentially another option to reduce the amount of typing and searching, depending on the specific use case.

C# is a purely object-oriented which means you cannot have functions or declarations outside of a class. You'll have to use static to achieve what you want.

Related

C++ named arguments, like C# [duplicate]

I've looked at both the Named Parameter Idiom and the Boost::Parameter library. What advantages does each one have over the other? Is there a good reason to always choose one over the other, or might each of them be better than the other in some situations (and if so, what situations)?
Implementing the Named Parameter Idiom is really easy, almost about as easy as using Boost::Parameter, so it kind of boils down to one main point.
-Do you already have boost dependencies? If you don't, Boost::parameter isn't special enough to merit adding the dependency.
Personally I've never seen Boost::parameter in production code, 100% of the time its been a custom implementation of Named Parameters, but that's not necessarily a good thing.
Normally, I'm a big fan of Boost, but I wouldn't use the Boost.Parameter library for a couple of reasons:
If you don't know what's going on,
the call looks like you're assigning
a value to a variable in the scope
on the calling function before
making the call. That can be very
confusing.
There is too much boilerplate code necessary to set it up in the first place.
Another point, while I have never used Named Parameter Idiom, I have used Boost Parameter for defining up to 20 optional arguments. And, my compile times are insane. What used to take a couple seconds, now takes 30sec. This adds up if you have a library of stuff that use your one little application that you wrote using boost parameter. Of course, I might be implementing it wrongly, but I hope this changes, because other than that, i really like it.
The Named Parameter idiom is a LOT simpler. I can't see (right now) why we would need the complexity of the Boost::Parameter library. (Even the supposed "feature" Deduced parameters, seems like a way to introduce coding errors ;) )
You probably don't want Boost.Parameter for general application logic so much as you would want it for library code that you are developing where it can be quite a time saver for clients of the library.
Never heard of either, but reviewing the links, named parameter is WAY easier and more obvious to understand. I'd pick it in a heartbeat over the boost implementation.

Is it possible to add keyword to C# or VB.NET?

I know it might not be worth it but just for education purposes I want to know if there is a way to inject your own keywords to .NET languages.
For example I thought it's good to have C++ asm keyword in C#.
Remember I'm not talking about how to implement asm keyword but a general way to add keyword to C#.
My imagined code :
asm{
mov ax,1
add ax,4
}
So is there a way to achieve this ?
The answers which cover implementing keyword{ } suits enough for this question.
This isn't possible at the moment. However, there's a Microsoft project in development called Roslyn that can be summarised as "the compiler as a service." It allows you, amongst other things, to extend or modify the behaviour of the compiler through an API.
When Roslyn becomes available, I believe this should be something that (with caution!) is quite doable.
You can use whatever tools you would like to pre-process your code before sending it to the C# compiler. For example, you might use VS macros to do the pre-processing, mapping a given syntax that you invented into something that does compile into C# code, possibly generating an error if there is a problem. If VS macros aren't powerful enough for you then you can always use your own IDE that does whatever you code it to do to the text before sending it to the compiler.
There is no built in support in the compiler for specifying your own keywords/syntax; you would need to handle it entirely independent of the compiler.
Unfortunately this is not possible. You can't extend or alter the languages in any way.
You could in some obscure way use PostSharp to read and parse strings and transform them to custom code at compile time (a pre processor). But you would not get very happy with that, as it is very error prone and you won't get any kind of intellisense or code completion for your magic strings.
According to MSDN keywords are predefined and cannot be altered. So you can't add any, because you would need to tell the compiler how to handle them. Insofar, no you can't.

What the various ways of calling a method at runtime?

I need to call a method on an object but I do not know the method name until runtime.
What are the techniques available?
(e.g. GetMethod().Invoke(), delegates, c# 4.0 dynamic)
Thanks!
The C# 4.0 dynamic functionality is going to be the easiest way to do this. In a very real sense, dynamic is "just a wrapper" around Reflection. It's a very good wrapper, though, that is probably your best option.
Other ways, in approximately increasing level of difficult:
Using a third-party Reflection
library. Not sure what's out there
these days.
Writing your own
Reflection code.
Use the CodeDOM to
create code that calls the method you
want to call.
Emit IL that does
pretty much the same thing as the
CodeDOM generated code.
Create C#
source code that you then compile
into an assembly that you can call,
which in turn calls the desired
method.
The last three are not for the faint of heart. Your best bet is to use dynamic or write your own Reflection code. If I had had dynamic three years ago when I was writing code for something similar, I would have used it.
You can use Reflection to call functions that you do not know the name of until run time. Here's some doc:
http://msdn.microsoft.com/en-us/library/f7ykdhsy%28VS.80%29.aspx

Convention for Filenames of Generic Classes [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to be able to distinguish between a generic and regular (non-generic) version of a class. Much like the .NET framework does with it's generic and non-generic versions of several of it's interfaces and collection classes. (Queue, Queue(T))
I generally like to follow the convention of one class per file (as in Java). Is there a common convention for naming files containing a single generic class? I'm mostly interested in Windows (NTFS specifically) but it seems like a good convention would be (at least a little) portable.
At Microsoft, they use ClassNameOfT.cs.
Just found this question after looking for what conventions other people use for generic class filenames.
Lately I've been using ClassName[T].cs. I really like this convention, and I think it's superior to the others for the following reasons:
The type parameters jump out at you a
little more than they do with the
Microsoft convention (e.g.,
ClassNameOfT.cs).
It allows you to have multiple
type parameters without too much
confusion: Dictionary[TKey,
TValue].cs
It doesn't require you to create any special folders, or to have your generic classes in a special namespace. If you only have a few generic classes, having a special namespace dedicated to them just isn't practical.
I borrowed this convention from Boo's generic syntax, albeit slightly modified (Boo uses ClassName[of T]).
Some developers seem to have a phobia of filenames that contain anything but letters and underscores, but once you can get past that this convention seems to work extremely well.
I see that this topic has been abandoned more than a year ago, but still I would like to share my view on this convention.
First of all, having multiple classes that have the same name but only differ in the amount of type-parameters isn't always a case of backwards compatibility. Surely, you don't see it very often, but the new Action- and Func-classes of .NET were just designed this way, and I'm currently implementing something similar.
For clarity and distinguishability, I use the following convention that only specifies the number of generic arguments for a given type:
MyClass.cs
MyClass.T1.cs
MyClass.T2.cs
This way, my filenames stay short and simple while still clearly communicating the class-name and the different amount of type parameters at the cost of a simple extra dot (which is, in my experience, a commonly accepted thing to do in a filename and looks much better than comma's and other non-alpanumeric characters, but this is just a matter of taste I guess). Putting the names (or acronyms) of the type parameters just lengthens the filenames while at this level I'm not really interested in the actual names of the type parameters anyway...
Don't use the grave accent ` in your generic file names if you're running Visual Studio 2008. There's a known issue with them that causes breakpoints to fail:
http://connect.microsoft.com/VisualStudio/feedback/details/343042/grave-accent-in-filename-causes-failure-to-recognize-target-language-breakpoints-fail
Personally I wouldn't use the grave accent notation:
Foo.cs
Foo`1.cs
For the simple reason that I am scared of the grave accent. Not only does it have a scary name 👻😨😱, but I am unsure how it will be handled by different file systems, version control systems and in URLs. Hence, I would prefer to stick to common alphanumeric characters.
NameOfT.cs seems to be used in ASP.NET Core according to a search on GitHub. 40 results. Reference.
Also used in the .NET Core runtime. 36 results. Reference.
Example:
Foo.cs
FooOfT.cs
Sometimes I also see ClassName{T}.cs but it is common to name it ClassNameOfT.cs (like mentioned before Microsoft uses it)
EntityFrameworkCore project(also Microsoft's) uses ClassName`.cs
All new Microsoft classes use generics. The Queue and ArrayList were there before generics came out. Generics is the way forward.
The convention for one-class-per-single file is to name the filename after the class name (whether generic of not). For MyClass, you'll have MyClas.cs. For every new namespace you'll need to create a new folder. This is how Visual Studio also works.
How about:
Type.cs
and
TypeGeneric.cs
Whenever I have done this in the past I have always put both types in one file with the non-generic type as the file name. I think that this makes things pretty clear as .NET has no conventions/restrictions on one type per file like Java does.
But if you must then I would suggest something like I have above, and using a suffix will make the files show up together in any alphabetized list (Solution Explorer, Windows Explorer, etc.).
Here is another idea:
Type`1.cs
This would allow you to break out different generic types by the number of generic type parameters they accepted. Its just a thought though as I still think it would be simpler to just put all the types in one file.
I would probably put them in folders and use the namespace mechanism instead. You can compare with System.Collections vs. System.Collections.Generic. On the other hand, if it's more common than not that the classes use generics, perhaps it's better to point out those that are not. That is if you really want to separate the generic classes from other classes. Personally I usually don't bother to do that, since I don't really see a practical benefit from it.
From the responses so far it seems there isn't a consensus.
Using the same filename in a sub-namespace (and sub-folder) "Generics" (like System.Collecctions.Generics) is an option. But it's not always desirable to create a new namespace.
For example, in an existing namespace with non-generic classes that are maintained for backwards compatibility, but marked with ObsoleteAttribute, it's probably better to keep the generic versions in the same namespace.
I think a suffix is a reasonable way to go. I've adopted a convention of using the type parameters as a suffix (so: MyClassT for MyClass<T>, or MyDictionaryKV for MyDictionary<K,V>.
I'd probably have two folders in the project, something like Gereric, NonGeneric or something like that. They can still be in the same namespace, and then they can both have the same file name. Just a thought...

Are default parameters bad practice in OOP?

Do default parameters for methods violate Encapsulation?
What was the rationale behind not providing default parameters in C#?
I would take this as the "official" answer from Microsoft. However, default (and named) parameters will most definitely be available in C# 4.0.
No, it doesn't affect encapsulation in any way. It simply is not often necessary. Often, creating an overload which takes fewer arguments is a more flexible and cleaner solution, so C#'s designer simply did not see a reason to add the complexity of default parameters to the language.
Adding "Another way to do the same thing" is always a tradeoff. In some cases it may be convenient. But the more syntax you make legal, the more complex the language becomes to learn, and the more you may wall yourself in, preventing future extension. (Perhaps they'd one day come up with another extension to the language, which uses a similar syntax. Then that'd be impossible to add, because it'd conflict with the feature they added earlier)
As has been noted, default parameters were not a prioritized feature, but is likely to be added in C# 4.0. However, I believe there were excellent reasons not to include it earlier (in 4.0, as I've understood it, itäs mostly to support duck typing styles of programming where default parameters increases type compatibility).
I believe excessive parameter lists (certainly more than 4-5 distinct parameters) is a code smell. Default parameters are not evil in themselves, but risk encouraging poor design, delaying the refactoring into more objects.
To your first question - no, it's exactly the same as providing multiple overloaded constructors. As for the second, I couldn't say.
Default parameters will be included in C# 4.0
Some reading material about it:
click
click
It also seems that the author of this post will publish an article in the near future on the 'why' MS chooses to implement default params in C#
Here is an answer why it's not provided in C#
http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx
One drawback with the default parameter implementation in C# 4.0 is that it creates a dependency on the parameters name. This already existed in VB, which could be one reason why they chose to implement it in 4.0.
Another drawback is that the default value depends on how you cast your object. You can read about it here: http://saftsack.fs.uni-bayreuth.de/~dun3/archives/optional-parameters-conclusion-treat-like-unsafe/216.html .

Categories