what does the global:: stand for in C# - c#

What does the global:: stand for in C#? for example what is the difference between
private global::System.Int32 myInt;
and
private int myInt;
Thanks

It's the "global" namespace - it forces the compiler to look for a name without taking other using directives into consideration. For example, suppose you had:
public class Bar{}
namespace Foo
{
public class Bar {}
public class Test
{
static void Main()
{
Bar bar1 = null; // Refers to Foo.Bar
global::Bar bar2 = null; // Refers to the "top level" Bar
}
}
}
Basically it's a way of avoiding naming collisions - you're most likely to see it in tool-generated code, where the tool doesn't necessarily know all the other types in the system. It's rarer to need it in manually-written code.
See "How to: Use the global namespace alias" on MSDN for more details, along with the :: namespace qualifier.

It is the global namespace alias.
If you declare a type called System.Int32 in your codebase, you can distinguish the built in .NET one using this alias.
// your code
namespace System
{
public class Int32
{
}
}
// You could reference the BCL System.Int32 like this:
global::System.Int32 bclInt;
System.Int32 myInt;
See How to: Use the Global Namespace Alias (C# Programming Guide) on MSDN.

It is used to refer to the global namespace. This is useful if you're writing code in a namespace that already exists elsewhere.
See this for more info: http://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx

Related

Namespace vs Class Declaration

I'm new to C# and I can't seem to find any info on this so I will ask it here.
Do classes in namespaces have to ever be declared?
using System;
public class myprogram
{
void main()
{
// The console class does not have to be declared?
Console.WriteLine("Hello World");
}
}
If I'm not using a namespace then I have to declare a class
class mathstuff
{
private int numberone = 2;
private int numbertwo = 3;
public int addhere()
{
return numberone + numbertwo;
}
using System;
public class myprogram
{
void main()
{
// the class here needs to be declared.
mathstuff mymath = new mathstuff();
Console.WriteLine(mymath.addhere());
}
}
Am I understanding this correctly?
A namespace is simply a way to make clear in which context the class is living in. Think of your own name, Ralph. We have many Ralphs in this world, but one of that is you. An extra way to get rid of the ambiguity is to add your surname. So that if we have 2 Ralphs, we have a bigger chance of talking about you.
The same works for classes. If you define class AClass and you would have the need of define another class AClass there would be no way to distinguish between the two. A namespace would be that 'surname'. A way of having to classes, but still able to distinguish between the two different classes, with the same name.
To answer your question, it has nothing to do with "not having to declare". It would only be easier to write code.
For example:
using System;
public class myprogram
{
void main()
{
// the class here needs to be declared.
Console.WriteLine("blah");
}
}
Because of the using System; you don't have to declare the namespace of Console. There is only one Console available, which lives in the System namespace. If you wouldn't declare your using System; namespace then you'd need to explain where Console can be found. Like this.
System.Console.WriteLine("blah");
From MSDN:
The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types.
For more info check MSDN for namespace.
I think what you mean is "can you declare a class without a namespace?". Yes you can, it's referred to as the global namespace.
class BaseClass
{
}
class SubClass : global::BaseClass
{
}
However, this is very bad practice, and you should never do this in a production application.

Delegates in practical scenario: within class scope Vs within namespace scope

What are the advantages-disadvantages of declaring a Delegate type within a class scope over declaring it directly within the namespace scope? I mean the following two -
namespace MyNamespace
{
public delegate string NamespaceScopeDelegate(int x, int y);
public class ClassX
{
//class members
}
}
and,
namespace YourNamespace
{
public class ClassA
{
public delegate string ClassScopeDelegate(int x, int y);
//...
//other class members
}
}
What sort of practical scenario would make me use the later one? I mean where exactly is it appropriate?
EDIT :
For the first case whenever I need to instantiate the delegate type, I can do that as -
var delegateInstance = new NamespaceScopeDelegate(MethodToPoint);
But for the second case, I must use the enclosing type name as -
var delegateInstance = new ClassA.ClassScopeDelegate(MethodToPoint);
Why would I want to do that? Does the second case provide any sort of encapsulation that I'm no aware of yet? Is there any special scenario that requires this sort of accessibility?
In your current examples, the only difference is that the second one doesn't clutter your namespace, you need to reference the class it is declared in first. You can use it to make clear that the delegate has a close relationship with the class and it is mostly used by it alone.
The following is also possible (either internal or private):
namespace YourNamespace
{
public class ClassA
{
internal/private delegate string ClassScopeDelegate(int x, int y);
//...
//other class members
}
}
By making it internal, only the same assembly can access it, and it doesn't clutter your namespace, by making it private, only the class itself may access the delegate declaration.
You need to understand that namespaces are just a nifty naming tool for your classes/delegates.
Take this code, for example:
namespace YourNamespace
{
public class ClassA
{
}
}
It produces a class with the name YourNamespace.ClassA. There isn't any actual namespace - just a class with dotted name notation.
The same is true for delegates defined inside classes.
What matters is how you wish to organize your code.
Simple as that.
What sort of practical scenario would make me use the later one?
For delegates, probably none.
From Nested Types as already mentioned in a comment:
Do not use nested types if the type is likely to be referenced outside of the declaring type. Declaration of variables and object instantiation for nested types should not be required in common scenarios. For example, an event-handler delegate that handles an event defined on a class should not be nested in the class.

VB.NET namespace abbreviation: How do I make this work in equivalent C# code?

I am a VB.NET programmer by nature and I am having a hard time figuring this out. Any help with the following would be appreciated.
I need to get the C# code (1) below to work. The VB.NET equivalent works just fine, but the C# does not.
Note that both (2) and (3) do work, but this is actually auto-generated code, and I need the VB.NET and C# versions to be as similar as possible.
This does not compile (the fully-qualified name of Engine is ThreeD.QVB.Engine):
using ThreeD.QVB;
namespace QVBScript
{
public class ScriptCode
{
public void Main(ref Engine.QVBObjectsDictionary objects,
Engine.Commands commands)
{
…
However, this does work:
//using ThreeD.QVB; // I'm instead using fully-qualified names in the method
namespace QVBScript
{
public class ScriptCode
{
public void Main(ref ThreeD.QVB.Engine.QVBObjectsDictionary objects,
ThreeD.QVB.Engine.Commands commands)
{
…
This works, too:
using eng = ThreeD.QVB.Engine;
namespace QVBScript
{
public class ScriptCode
{
public void Main(ref eng.QVBObjectsDictionary objects,
eng.Commands commands)
{
…
In VB.NET if you have an import for the first part of a namespace, you can reference just the later half. In C# you cannot do this. You must have a using for the full namespace, or fully qualify your type names. Different languages, different rules.
In your last example you do not need to use the alias.
using ThreeD.QVB.Engine;
namespace QVBScript
{
public class ScriptCode
{
public void Main(ref QVBObjectsDictionary objects, Commands commands)
{
UI.Output Output = (UI.Output)objects["Output"];
Basic rules to remember:
using A.B;
does allow you to refer to types from namespaces A and A.B without fully qualifying them with their namespace (everywhere in the same file).
does not allow you to abbreviate the names of sub-namespaces of A or A.B. by omitting the A. or A.B. part from their names.
namespace A.B { … }
does allow you to refer to types from namespaces A and A.B without fully qualifying them with their namespace (inside the block).
does allow you to abbreviate the names of sub-namespaces of A or A.B by omitting the A. or A.B. part from their names.
Example:
using System.Collections;
namespace A
{
class Top : IDisposable, // importing System.Collections also imports System
IEnumerable, // inside the imported namespace
System.Collections.Generic.IEnumerable<int>
{…} // ^ "using" does not permit namespace abbreviation
}
namespace A.B
{
class Middle : Top, // namespace A available inside namespace A.B
C.IBottom // namespace blocks permit namespace abbreviation
{…}
}
namespace A.B.C
{
interface IBottom {…}
}

How to reference the type of a private class from an assembly-level attribute?

I have defined an assembly level attribute class FooAttribute like this:
namespace Bar
{
[System.AttributeUsage (System.AttributeTargets.Assembly, AllowMultiple=true)]
public sealed class FooAttribute : System.Attribute
{
public FooAttribute(string id, System.Type type)
{
// ...
}
}
}
and I use it to associate an id to classes, for instance:
[assembly: Bar.Foo ("MyClass", typeof (Bar.MyClass))]
namespace Bar
{
public class MyClass
{
private class Mystery { }
}
}
This all works fine. But what if I need to somehow reference the private class Mystery, defined in MyClass? Is this at all possible? Trying to reference it from the top-level [assembly: ...] directive does not work, as the type is not publicly visible:
[assembly: Bar.Foo ("Mystery", typeof (Bar.MyClass.Mystery))] // won't work
And trying to put the [assembly: ...] directive into MyClass in so that it could see Mystery is not legal, as [assembly: ...] must be defined at the top level:
namespace Bar
{
class MyClass
{
[assembly: FooAttribute (...)] // won't work either
...
}
}
There is a way to access internal types from outside of an assembly by declaring the user a friend of the assembly, but how about referencing private types inside an assembly? I guess it is not possible, and I just would have to declare Mystery to be internal instead, but I want to be sure I did not miss some subtlety.
Making it internal (which you already state you don't want to do) is the least effort approach. For the majority of code, allowing MyClass to expose (via a static property) the type instance (i.e. public static Type MysteryType { get { return typeof(Mystery); } } would work, but that won't work from an attribute (only constant values of a few basic types can be used).
The only alternative to internal, then, is to code it as a string literal, (i.e. [Foo("Bar.MyClass+Mystery")]) and use typeof(MyClass).Assembly.GetType(fullName) - but then you lose the compiler validation that typeof normally provides. (note also the + that the runtime uses to represent nested types, not . which is the C# representation)
Personally, I'd just make it internal.
Your assertions in your last paragraphs are correct. Your options would be to:
Make the nested class internal to enable typeof
or
Have an added constructor to FooAttribute which takes the fully qualified type name of the private nested class, and then uses reflection to get a System.Type representing it.
For instance:
public sealed class FooAttribute
{
public FooAttribute(string id, string typeName)
{
var type = Type.GetType(typeName);
// whatever the other ctor does with the System.Type...
}
}
usage:
[assembly: Foo("Bar", typeof(Bar))]
[assembly: Foo("Baz", "Foo.Bar+Baz, MyAssembly")]
namespace Foo
{
public class Bar
{
private class Baz
{
}
}
}

Namespace-only class visibility in C#/.NET?

In C#, can you make a class visible only within its own namespace without living in a different assembly? This seems useful for typical helper classes that shouldn't be used elsewhere.
(i.e. what Java calls package-private classes)
You can make the classes internal but this only prevents anyone outside of the assembly from using the class. But you still have to make a separate assembly for each namespace that you want to do this with. I'm assuming that is why you wouldn't want to do it.
Getting the C# Compiler to Enforce Namespace Visibility
There is an article here (Namespace visibility in C#) that shows a method of using partial classes as a form of "fake namespace" that you might find helpful.
The author points out that this doesn't work perfectly and he discusses the shortcomings. The main problem is that C# designers designed C# not to work this way. This deviates heavily from expected coding practices in C#/.NET, which is one of the .NET Frameworks greatest advantages.
It's a neat trick… now don't do it.
I don't think that what you want is possible.
internal is assembly (strictly speaking module) privacy. It has no effect on namespace visibility.
The only way to achieve privacy of a class from other classes within the same assembly is for a class to be an inner class.
At this point if the class is private it is invisible to anything not in that class or the outer class itself.
If protected it is visible to everyone that could see it when private but is also visible to sub classes of the outer class.
public class Outer
{
private class Hidden { public Hidden() {} }
protected class Shady { public Shady() {} }
public class Promiscuous { public Promiscuous() {} }
}
public class Sub : Outer
{
public Sub():base()
{
var h = new Hidden(); // illegal, will not compile
var s = new Shady(); // legal
var p = new Promiscuous(); // legal
}
}
public class Outsider
{
public Outsider()
{
var h = new Outer.Hidden(); // illegal, will not compile
var s = new Outer.Shady() // illegal, will not compile
var p = new Outer.Promiscuous(); // legal
}
}
In essence the only way to achieve what you desire is to use the outer class as a form of namespace and restrict within that class.
No, it is possible. You can use internal class in another assembly.
For example I have a internal string extension class that located in SharMillSoft.Core assembly, if I want use it in another assembly that name is SharpMilSoft.Extension, I must use assembly attribute like as below:
using System;
using System.Linq;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("SharpMilSoft.Extensions")]
namespace SharpMilSoft.Core.Extensions.Strings.Public
{
internal static class SharpStringExtensions
{
public static bool IsNullOrEmpty(this string data)
{
return string.IsNullOrEmpty(data);
}
}
}
And I use this class in SharpMilSoft.Extension assembly like as below:
namespace SharpMilSoft.Extensions.Strings
{
public static class SharpStringExtensions
{
public static bool IsNullOrEmpty(this string data)
{
return Core.Extensions.Strings.Public.SharpStringExtensions.IsNullOrEmpty(data);
}
}
}
Note: Then SharpMilSoft.Extensions assembly will be friend assembly for SharpMilSoft.Core assembly
For more details about friend assembly, you can visit this link : Friend assemblies
If you have a single assembly you can define as many namespaces in that assembly as you want but no matter what modifier you apply in the IDE you will always be able to see the classes in other namespaces.
Not sure if it is directly possible, but a few good ways to fake it would be:
1) Have the classes that need this sort of stuff inherit from a single class which has the helper class as an internal class.
2) Use extension methods and then only reference the extension methods within the namespace.

Categories

Resources