So I was going through some older code at work and came across this:
using Int16 = System.Int16;
using SqlCommand = System.Data.SqlClient.SqlCommand;
I have never seen a Namespace Declaration use an '=' before. What's the point of using it? Are there any benefits declaring things this way?
What else strikes me as odd is the fact that they even bothered declaring Int16. Doesn't visual studio know what an Int16 is just by typing it out?
The first line makes... erm... little sense, but it's not a namespace import; it is a type alias. For example, int is an alias for Int32. You are perfectly free to create your own aliases as you show in your example.
For example, let's say you have to imported namespaces with two types with the same name (System.Drawing.Point and System.Windows.Point come to mind...). You can create an alias to avoid fully qualifying the two types n your code.
using WinFormsPoint = System.Drawing.Point;
using WpfPoint = System.Windows.Point;
void ILikeMyPointsStructy( WinFormsPoint p ) { /* ... */ }
void IPreferReferenceTypesThankYou( WpfPoint p ) { /* ... */ }
The namespace alias is good for simplifying how you access certain types-- especially when you have many types with conflicting names.
For example, if you are referencing a couple of different namespaces where you've defined different sets of constants like:
namespace Library
{
public static class Constants
{
public const string FIRST = "first";
public const string SECOND = "second";
}
}
namespace Services
{
public static class Constants
{
public const string THIRD = "third";
public const string FOURTH = "fourth";
}
}
Then you decide to use both in a code file-- you will get a compilation error just by writing:
var foo = Constants.FIRST;
The alternative is to fully qualify your constants, which can be a pain, so the namespace alias simplifies it:
using Constants = Library.Constants;
using ServiceConstants = Service.Constants;
That being said, I don't know why you'd alias an Int16 as an Int16!
For those developers coming from a C++ background the construct can also be used as a sort of "local typedef" which helps simplify generic container definitions:-
using Index = Dictionary<string, MyType>;
private Index BuildIndex(. . .)
{
var index = new Index();
. . .
return index;
}
Related
The code looks like this.
public class One<T> where T : Two {
public static int Y;
static One() {
// Y is to be initialised with the Z value from T
// this code does not compile
// Y = T.Z;
}
public int X { get { return Y; } }
}
public class Two {
public static int Z = 42;
}
public class Three {
public void Main() {
One<Two> a = new One<Two>();
Console.WriteLine("X = {0}", a.X); // should say 42
}
}
The idea is very simple: initialise the static value in a class from another static value in another class passed as a type parameter. There is nothing 'unsafe' about this, but the natural way to do it does not compile (see code).
I've searched SO and found a few near misses, but nothing that hits the spot. I've tried a few things including reflection, but to no avail. Any solution or even hints much appreciated.
Flydog's given you something you could use; I just wanted to make a quick note about my/jimi/enigmativity's comments:
It feel like you're hoping to subclass Two at some point and change out the Z; you reason that if your new class Three, which has a static Z of 43 and derives from Two, is used in combination with One then you'll end up with an .X that is 43. The problem comes in that static things cannot be overridden; they're resolved at compile time and they can look like overriding is at play in certain circumstances, but it's actually overloading or hiding and the compiler is picking something with a particular name in a defined order out of the inheritance tree
Because static things don't inherit (and arguably don't need to because they are hence always known to you, the developer, at compile time) there isn't the expectation that one day someone will subclass your code and write :
One<Four> a = new One<Four>();
And your code will need to pick up whatever they set Z to and use it. You know your Zs and can use them appropriately at compile tine and they know their Zs and should use them appropriately. But I understood where you were going with the T.Z thing..
It almost looks like it should work. Then you start typing T.Z and realize that your gut is agreeing with the compiler. T is a type parameter, it isn't a full fledged type-y thing.
Anyways, this works:
static One()
{
// Y is to be initialised with the Z value from T
var typeT = typeof(T);
var zFieldInfo = typeT.GetField("Z");
Y = (int) zFieldInfo.GetValue(null);
}
Yeah, it uses reflection, but it's only ever going to be run once.
I understand in C# there is such thing as named parameters so that is a bit misleading. The question I have is what they should be called in general.
In my time using libraries in other languages I've sometimes run across predefined values that can be used within functions of a class.
object.myFunc(SPECIAL_VALUE);
It's usually named in all capitol letters and is a very specific value within the function. I figure it behaves much like a public static string but when I use this idea intellisense doesn't pick this up. Can someone inform me of the general name of this kind of parameter option and if they exist, pros and cons of using such a thing.
Thanks,
Normally, those kind of constants in C# are declared and cased like this...
public const String MyConstantThingHere = "Some value";
In Java, it would be more like...
public static final String MY_CONSTANT_THING_HERE = "Some value";
I would simply call these public class constants. See HERE.
Also, for reference: http://www.dofactory.com/reference/csharp-coding-standards
You can also use static imports to refer to them...
See here: static imports in c#
I'm not really sure, what you mean. The concept of named parameters in C# is shown in this example:
namespace Testconsole {
public class obj {
public int myFunc(int value1, int value2 = 4, int value3 = 8) {
return value1 + value2 + value3;
}
}
class Program {
static void Main(string[] args) {
obj adder = new obj();
Console.WriteLine(adder.myFunc(value1: 1, value3: 1));
Console.ReadLine();
}
}
}
Testconsole returns 6: value1 is set with '1', value3 is set with '1', value2 is missing and therefore filled with default value '4'.
Also it is possible to pass a public static String into a Function:
namespace Testconsole {
public class obj {
public String myFunc(String mySpecialValue) {
return "now I " + mySpecialValue;
}
}
class Program {
public static String SPECIAL_VALUE = "got it";
static void Main(string[] args) {
obj Learn = new obj();
Console.WriteLine(Learn.myFunc(SPECIAL_VALUE));
Console.ReadLine();
}
}
}
Console output:
Now I got it.
What you are referring to is a "constant." They serve two purposes:
They ensure that a value that has some meaning (a "special value", as you said) is declared in one place and re-used so that if it changes we change it in one place.
They make our code more readable. For example, we might want two always display the top four items from a list on a web page. And we might have an input that should always be four characters in length. If other people just read our code and see the number 4 here and there it might not be apparent what that number 4 means. We want our code to be as easy to understand as possible.
So when we declare
const int NUMBER_OF_ITEMS_TO_DISPLAY = 4
or
const string MAX_INPUT_LENGTH_SETTINGS_KEY = "maximumInputLength"
Then when we use those constants in our code other people can tell what they mean.
The opposite of using constants is called using "magic numbers" or "magic strings." They just appear in our code without context or explanation. It might just be value we arbitrarily picked, but declaring it as a constant gives it context and meaning.
The capital letters aren't required. They're just a convention that makes constants easy to recognize.
What is this Type in .NET? I am using reflection to get a list of all the classes and this one turns up.
What is it? where does it come from? How is the name DisplayClass1 chosen? I search the sources and didnt see anything. What does the <> mean? what does the c__ mean? is there reference?
It's almost certainly a class generated by the compiler due to a lambda expression or anonymous method. For example, consider this code:
using System;
class Test
{
static void Main()
{
int x = 10;
Func<int, int> foo = y => y + x;
Console.WriteLine(foo(x));
}
}
That gets compiled into:
using System;
class Test
{
static void Main()
{
ExtraClass extra = new ExtraClass();
extra.x = 10;
Func<int, int> foo = extra.DelegateMethod;
Console.WriteLine(foo(x));
}
private class ExtraClass
{
public int x;
public int DelegateMethod(int y)
{
return y + x;
}
}
}
... except using <>c_displayClass1 as the name instead of ExtraClass. This is an unspeakable name in that it isn't valid C# - which means the C# compiler knows for sure that it won't appear in your own code and clash with its choice.
The exact manner of compiling anonymous functions is implementation-specific, of course - as is the choice of name for the extra class.
The compiler also generates extra classes for iterator blocks and (in C# 5) async methods and delegates.
Jon is of course correct. I've provided a "decoder ring" for figuring out what the various compiler-generate type names mean here:
Where to learn about VS debugger 'magic names'
The names are quite long and we sometimes get complaints that we're bulking up the size of metadata as a result. We might change the name generation rules to address this concern at any time in the future. It is therefore very important that you not write code that takes advantage of knowledge of this compiler implementation detail.
This one's really an offshoot of this question, but I think it deserves its own answer.
According to section 15.13 of the ECMA-334 (on the using statement, below referred to as resource-acquisition):
Local variables declared in a
resource-acquisition are read-only, and shall include an initializer. A
compile-time error occurs if the
embedded statement attempts to modify
these local variables (via assignment
or the ++ and -- operators) or
pass them as ref or out
parameters.
This seems to explain why the code below is illegal.
struct Mutable : IDisposable
{
public int Field;
public void SetField(int value) { Field = value; }
public void Dispose() { }
}
using (var m = new Mutable())
{
// This results in a compiler error.
m.Field = 10;
}
But what about this?
using (var e = new Mutable())
{
// This is doing exactly the same thing, but it compiles and runs just fine.
e.SetField(10);
}
Is the above snippet undefined and/or illegal in C#? If it's legal, what is the relationship between this code and the excerpt from the spec above? If it's illegal, why does it work? Is there some subtle loophole that permits it, or is the fact that it works attributable only to mere luck (so that one shouldn't ever rely on the functionality of such seemingly harmless-looking code)?
I would read the standard in such a way that
using( var m = new Mutable() )
{
m = new Mutable();
}
is forbidden - with reason that seem obious.
Why for the struct Mutable it is not allowed beats me. Because for a class the code is legal and compiles fine...(object type i know..)
Also I do not see a reason why changing the contents of the value type does endanger the RA. Someone care to explain?
Maybe someone doing the syntx checking just misread the standard ;-)
Mario
I suspect the reason it compiles and runs is that SetField(int) is a function call, not an assignment or ref or out parameter call. The compiler has no way of knowing (in general) whether SetField(int) is going to mutate the variable or not.
This appears completely legal according to the spec.
And consider the alternatives. Static analysis to determine whether a given function call is going to mutate a value is clearly cost prohibitive in the C# compiler. The spec is designed to avoid that situation in all cases.
The other alternative would be for C# to not allow any method calls on value type variables declared in a using statement. That might not be a bad idea, since implementing IDisposable on a struct is just asking for trouble anyway. But when the C# language was first developed, I think they had high hopes for using structs in lots of interesting ways (as the GetEnumerator() example that you originally used demonstrates).
To sum it up
struct Mutable : IDisposable
{
public int Field;
public void SetField( int value ) { Field = value; }
public void Dispose() { }
}
class Program
{
protected static readonly Mutable xxx = new Mutable();
static void Main( string[] args )
{
//not allowed by compiler
//xxx.Field = 10;
xxx.SetField( 10 );
//prints out 0 !!!! <--- I do think that this is pretty bad
System.Console.Out.WriteLine( xxx.Field );
using ( var m = new Mutable() )
{
// This results in a compiler error.
//m.Field = 10;
m.SetField( 10 );
//This prints out 10 !!!
System.Console.Out.WriteLine( m.Field );
}
System.Console.In.ReadLine();
}
So in contrast to what I wrote above, I would recommend to NOT use a function to modify a struct within a using block. This seems wo work, but may stop to work in the future.
Mario
This behavior is undefined. In The C# Programming language at the end of the C# 4.0 spec section 7.6.4 (Member Access) Peter Sestoft states:
The two bulleted points stating "if the field is readonly...then
the result is a value" have a slightly surprising effect when the
field has a struct type, and that struct type has a mutable field (not
a recommended combination--see other annotations on this point).
He provides an example. I created my own example which displays more detail below.
Then, he goes on to say:
Somewhat strangely, if instead s were a local variable of struct type
declared in a using statement, which also has the effect of making s
immutable, then s.SetX() updates s.x as expected.
Here we see one of the authors acknowledge that this behavior is inconsistent. Per section 7.6.4, readonly fields are treated as values and do not change (copies change). Because section 8.13 tells us using statements treat resources as read-only:
the resource variable is read-only in the embedded statement,
resources in using statements should behave like readonly fields. Per the rules of 7.6.4 we should be dealing with a value not a variable. But surprisingly, the original value of the resource does change as demonstrated in this example:
//Sections relate to C# 4.0 spec
class Test
{
readonly S readonlyS = new S();
static void Main()
{
Test test = new Test();
test.readonlyS.SetX();//valid we are incrementing the value of a copy of readonlyS. This is per the rules defined in 7.6.4
Console.WriteLine(test.readonlyS.x);//outputs 0 because readonlyS is a value not a variable
//test.readonlyS.x = 0;//invalid
using (S s = new S())
{
s.SetX();//valid, changes the original value.
Console.WriteLine(s.x);//Surprisingly...outputs 2. Although S is supposed to be a readonly field...the behavior diverges.
//s.x = 0;//invalid
}
}
}
struct S : IDisposable
{
public int x;
public void SetX()
{
x = 2;
}
public void Dispose()
{
}
}
The situation is bizarre. Bottom line, avoid creating readonly mutable fields.
Could you create an object from a class named Trung.NguyenThe since NguyenThe isn't a method ?
In Java C# and Ruby, you cannot create variables with a . in the name.
// C# and Java
Object Trung.NguyenThe = "";
# Ruby
Trung.NguyenThe = ""
That variable name is illegal in all three languages.
If you want to do something similar to this, use an underscore _.
// C# and Java
Object Trung_NguyenThe = "";
# Ruby
Trung_NguyenThe = ""
First of all, objects do not have names. Classes and variables do.
So I'll assume you're asking about naming classes with periods (based on your last comment)...
The straight answer is "no", but one can emulate that using namespaces/packages or inner classes.
Namespace:
namespace Trung {
public class NguyenThe {}
}
// Usage:
namespace Whatever {
public class Client {
public main() {
var x = new Trung.NguyenThe();
}
}
}
Inner class:
namespace Whatever {
public class Trung {
public class NguyenThe {}
}
// Usage:
public class Client {
public main() {
var x = new Trung.NguyenThe();
}
}
}
(Note: This is C# code, but I'm sure the same could be done in Java. I guess Ruby has the same concepts also.)
In Ruby, there's no such thing as a class name. Classes are just objects like every other object which get assigned to variables just like any other variable.
Trung.NguyenThe is not a legal variable name, therefore this is impossible:
class Object
klass = Class.new do
def to_s; 'Hello' end
end
const_set :'Trung.NguyenThe', klass
# NameError: wrong constant name Trung.NguyenThe
end
You could, of course, create an object which responds to a NguyenThe message with a class and assign that object to a variable named Trung, but that's not what you are asking about:
klass = Class.new do
def to_s; 'Hello' end
end
(Trung = Object.new).define_singleton_method(:NguyenThe) { klass }
puts Trung.NguyenThe.new
# Hello
In C# and Java, periods are illegal in class names as well. C# has an escaping mechanism that allows you to use otherwise reserved words as names, but this mechanism doesn't make it possible to use illegal names, only reserved ones.
There are proposals for more symbolic freedom in Java names, but so far, they have not yet been implemented.
Sure. Create a package called Trung. Within this package create a class called NguyenThe.
Or are you assuming that Trung is already a class name?