How to define "anonymous namespace" in C#? - c#

In C++, in order to define a symbol that is only accessible within the same file, we say
namespace
{
class my_private_class
{ ... }
}
But can I do the same thing in C#? Or do I have to say
namespace __DO_NOT_USE_OUT_OF_.xxx.cs__
{
public MyPrivateClass
{ ... }
}
using __DO_NOT_USE_OUT_OF_.xxx.cs__;
(assuming this is in a file called xxx.cs)?
The later, of cause, will depend on the other programmer regards it or not.

There's no anonymous namespaces in C#, but you can exploit static classes:
namespace MyNamespace // <- Just a namespace
{
// Anonymous Namespace emulation:
// static class can't have instances and can't be inherited,
// it's abstract and sealed
internal static class InternalClass // or public static class
{
// private class, it's visible within InternalClass only
class my_private_class
{ ... }
}
}

There is no such thing in C#, we have something called access modifiers which manage the visibility of types.
The usage is against a class or method, such as:
internal class MyType
{
}
Or
protected void MyMethod()
{
}
You will have to pick the one that applies to your scenario, here are the details:
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

Related

Can't derive class from abstract System.Drawing.Image class [duplicate]

I want to inherit a class from another class, marked as abstract, that not have any constructor defined.
This is my code:
// In one assembly (TheMessage.dll), as seen via F12 in VS (from Metadata)
namespace Namespace1
{
public abstract class Message
{
public string Body { get; set; }
// some abstract methods here, not shown.
}
}
// In another assembly (TheUser.dll)
namespace Namespace2
{
public class MyMessage : Namespace1.Message
{
public MyMessage()
{
}
}
}
The problem is that on the public MyMessage() constructor I get the error
The type 'Namespace1.Message' has no constructors defined
I saw on MSDN site (abstract (C# Reference) first example) that inheriting an abstract class without constructor is possible. So, anyone know why I get this error?
Note that one can inherit just fine when type is in the same DLL as the Message class and it works as that assembly exposes some other types deriving from Namespace1.Message similar to following:
// The same assembly as Message (TheMessage.dll), as seen via F12 in VS (from Metadata)
namespace Namespace3
{
public class Message : Namespace1.Message
{
public Message() {}
public Message(string to) {}
}
}
I've also checked The type '...' has no constructors defined, but it does not speak about inheritance but rather just new-ing up an instance and I clearly have no expectations to directly instantiate an instance of an abstract class.
You probably have an internal constructor (not shown in the code that you posted) and are trying to instantiate the class with the internal constructor from a different assembly.
(The default constructor for a base class is automatically called from a derived class if you don't explicitly specify a base class constructor to call, so it might not be obvious to you that the base class constructor is being called.)
For example, if one assembly contains this class (inside namespace ClassLibrary1):
public class Base
{
internal Base()
{
}
}
And a DIFFERENT assembly does this:
class Derived: Base
{
public Derived()
{
}
}
You will see the following compile error:
The type 'ClassLibrary1.Base' has no constructors defined
If none of the instance constructors of the Message class are visible to you (typically because they are all private and you are outside the class, or they are all private or internal and you are outside the assembly), you cannot write a class that inherits from Message. (Well, you could make two instance constructors which chain each other cyclicly with the :this(...) syntax, but that would not be useful).
Note that when you look at the "metadata" (reflection generated pseudo-C# for an assembly you refer), you typically only see the "visible" members, so any private or internal members will not show up. I think you look at the metadata because we see non-abstract (and non-extern) methods whoses bodies are absent (just a semicolon ; there instead of a body { ... }).
The source code of your Message class will have one or more constructors, each private or internal, but when seen from outside the assembly, these are "non-existent".
If the source code of a non-static C# class Message contains no instance constructors, the compiler will generate one automatically. It will be a public parameterless constructor if the class is concrete (i.e. non-abstratc), and a protected one if the class is abstract.
That means that if the source code looks like this:
public abstract class Message
{
// note: zero non-static constructors here
}
it will be compiled exactly as if it had said:
public abstract class Message
{
protected Message()
{
}
}
and in that case the generated instance constructor is accessible to all classes deriving from Message.

Understanding Access specifiers on Classes in C#

First of all let me start by saying that I do understand access specifiers I just don't see the point of using them in classes. It makes sense on methods to limit their scope but on classes, why would you want a private class, isn't it the purpose of classes to be able to reuse them?
What is the purpose of access specifiers when declaring a class in C#? When would you use them?
Thanks
Well, let's say that you want a class to be only accessed inside her own assembly:
internal class Test
Let's say that you have two classes, one inside the other (nested classes):
protected internal class TestA
{
private TestB _testB;
private class TestB
{
}
public TestA()
{
_testB = new TestB();
}
}
The TestB class can be only accessed inside methods/properties/contructors inside TestA or inside herself.
The same applies to the protected modifier.
// Note
If you don't specify the access modifier, by default it will be private, so on my example the following line:
private TestB _testB;
is equal to
TestB _testB;
And the same applies to the class.
Special Modifier
Then, there is the protected internal which joins both modifiers so you can only access that class inside the same assembly OR from a class which is derived by this one even if it isn't in the same assembly. Example:
Assembly 1:
public class TestA : TestB
{
public TestB GetBase()
{
return (TestB)this;
}
public int GetA1()
{
return this.a1;
}
}
protected internal class TestB
{
public int a1 = 0;
}
Program
TestA _testA = new TestA(); // OK
TestB _testB = new TestB(); // ERROR
int debugA = new TestA().a1 // ERROR
int debugB = new TestA().GetA1(); // OK
TestB testB_ = new TestA().GetBase(); // ERROR
Source
Link (Access Modifiers)
Internal
The type or member can be accessed by any code in the same assembly,
but not from another assembly.
Private
The type or member can be accessed only by code in the same class or
struct.
Protected
The type or member can be accessed only by code in the same class or
struct, or in a class that is derived from that class.
Public
The type or member can be accessed by any other code in the same
assembly or another assembly that references it.
I will give you an example of an internal class. Imagine I have some DLL. Form this DLL I want to expose only a single class called A. This class A however, should have access to other classes inside DLL - thus I will make all other classes inside DLL internal. Hence, from the DLL you can only use class A, while A can still access other classes inside DLL - you however, can't.
The greatest benefit of using access specifiers is when someone else is using your classes. By clearly specifying, what should and what should not be touched within your objects, you can protect your object internal mechanism and integrity from being misused or damaged.
With bigger classes, if you made everything public, you would also make it harder for the user of your code to work with IntelliSense, which is something that is very handy when you deal with unknown libraries.
I have created one application to understand Access Specifiers.
It will be more easy to understand it with code instead of Theory.
I have added my notes in code, for better guidance.
namespace ConsoleApplication1
{
//A normal public class which contains all different types of access-modifier classes in the assembly named 'ConsoleApplication1'
public class Base
{
public class PublicBase
{
public static void fn_PublicBase()
{
Console.WriteLine("fn_PublicBase");
}
}
private class PrivateBase
{
public static void fn_PrivateBase()
{
Console.WriteLine("fn_PrivateBase");
}
}
protected class ProtectedBase
{
public static void fn_ProtectedBase()
{
Console.WriteLine("fn_ProtectedBase");
}
}
internal class InternalBase
{
public static void fn_InternalBase()
{
Console.WriteLine("fn_InternalBase");
}
}
protected internal class ProInternalBase
{
public static void fn_ProInternalBase()
{
Console.WriteLine("fn_ProInternalBase");
}
}
//TIP 1:This class is inside the same class 'Base' so everything is accessible from above.Hurray!!
class Base_Inside
{
public static void fn_Base_Inside()
{
//All methods are easily accessible.Does not consider a modified indeed.
PublicBase.fn_PublicBase();
PrivateBase.fn_PrivateBase();
ProtectedBase.fn_ProtectedBase();
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
//Different class but inside the same assembly named 'ConsoleApplication1'
public class Base_Sibling : Base
{
//TIP 2:This class is NOT in same class 'Base' but in the same assembly so only protected is NOT accessible rest all are accessible.
public void fn_Base_Sibling()
{
PublicBase.fn_PublicBase();
//PrivateBase.fn_PrivateBase(); //ERROR:Accesibility of 'protected'
ProtectedBase.fn_ProtectedBase(); //protected is accessible because Base_Sibling inherit class 'Base'. you can not access it via Base.ProtectedBase
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
Now to Understand difference between internal, protected internal,
I Have added one for project named with Assembly_1 in same
solution.
I have inherited Base class of ConsoleApplication1 to Derived class of Assembly_1.
namespace Assembly_1
{
//TIP:if it does not inherit class 'ConsoleApplication1.Base' then we can not access any thing beacuse this is different assembly.
//TIP:only INTERNAL is NOT accessible , rest all are accessible from first assembly if it inherits class 'Soul'
public class Derived : ConsoleApplication1.Base
{
public class PublicDerived
{
public static void fn_PublicDerived()
{
PublicBase.fn_PublicBase(); //YES, becuase this is 'public'
//PrivateBase.fn_PrivateBase(); //No, becuase this is 'private'
ProtectedBase.fn_ProtectedBase(); //YES, becuase this is 'protected'
//InternalBase.fn_InternalBase(); //No, becuase this is 'internal'
ProInternalBase.fn_ProInternalBase(); //YES, becuase this is 'protected internal'
}
}
}
}
- Update answer 2019 -
Hi You can find accessibility via below table

Why protected internal class cannot derive?

Scope of the protected internal is same assembly, or by any derived class in another assembly.Then Why protected internal class cannot derive?
Sample code:
protected internal class AbsClass
{
int m = 50;
public int am = 5;
public void nonAbsfn()
{
Console.WriteLine(m + am);
}
}
class TestAbstract : AbsClass
{
}
A class can only be protected internal if it is an inner class.
Otherwise, a class can only be public or internal.
To fix your compilation error, make the class either public or internal. The error you are getting has nothing to do with the derived class TestAbstract.
According to the MSDN documentation:
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
So you should be able to do it. Can you post some of your code?

Inconsistent accessibility: base class is less accessible than child class

I am reading book "C# 4.0 in a nutshell" by Joseph Albabari and Ben Albabari. From there I find a topic restrictions on access modifiers. Page 91, Topic "Restrictions on Access Modifiers".
Quoting from the book.
The compiler prevents any inconsistent use of access modifiers. For
example, a sub- class itself can be less accessible than a base class,
but not more
So this says that base class should be equally or more accessible than subclass. So if base class is internal then subclass should be either private or internal. If base class is private and sub class is public then compile time error will be generated. While trying this in Visual Studio I found some strange behavior.
Try 1: Base is private and sub class is private (Works, right behavior) This also works if both are internal, public.
private class A { }
private class B : A { } // Works
Try 2: Base is private and sub class is public or internal (This fails, right behavior)
private class A { }
public class B : A { } // Error
Try 3 : Base is internal and sub is public (This works, but it should fail. As Base is less accessible than sub class
internal class A { }
public class B : A { } // Works, but why
Now my question is why Try 3 didn't failed? Sub class is public and is more accessible than base class which is internal. Even the book says this should fail. But Visual Studio compiled this successfully. This should work or not?
Edit:
I created a new Console Project in VS. In Program.cs I added my code. Here is complete code of Program.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication
{
class Program
{
internal class A { }
public class B : A { } // Error
static void Main()
{
}
}
}
You are placing your nested classes within another internal class.
For example, given:
class Program
{
static void Main(string[] args)
{
}
internal class A { }
public class B : A { }
}
It will compile because the internal modifier of the wrapping class makes the public modifier on class B moot. Rather, type B's accessibility is limited by its wrapped class Program -- its accessibility domain is internal as well.
If you update it to be:
class Program
{
static void Main(string[] args)
{
}
}
internal class A { }
public class B : A { }
It will throw the inconsistent visibility compiler error. Or if you redefine Program to be public instead of internal it will also throw the error. In this case, B's accessibility domain is now public and no longer limited by Program's internal accessibility domain.
From the C# specification 3.5.2 Accessibility Domains:
The accessibility domain of a nested member M declared in a type T
within a program P is defined as follows (noting that M itself may
possibly be a type):
If the declared accessibility of M is public, the accessibility domain of M is the accessibility domain of T.
And the MSDN's description of Accessibility Domain:
If the member is nested within another type, its accessibility domain
is determined by both the accessibility level of the member and the
accessibility domain of the immediately containing type.
If the wrapping type Program is internal, then the nested type B being public will have its accessibility to match Program, thus it is treated as internal and no compiler error is thrown.
private inherited classes can not accessible in other classes when you inherit private class with other public class then it contains the reference of private class and its data so it is not possible.
abstract class test
{
public abstract void add();
public int num1;
public string str;
}
class test3 : test1
{
public override void add()
{
throw new NotImplementedException();
}
}
both classes are private.
if you use internal then you can access only in assembly.

Why elements defined in a namespace cannot be explicitly declared?

I have the following C# code:
namespace ISeeOptic.BL
{
public abstract class Process
{
...
protected static void DeleteImages(List<ImagesPath> list)
{
some logic
}
...
}
protected class GetDataBL: Process
{
...
public static void DeleteImages(List<ImagesPath> list)
{
DeleteImages(list);
}
...
}
}
At compile-time I get the following Error:
Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
I'm beginner in C# so maybe this question may seem naive,
any idea what cause to this error?
Thank you advance.
Elements defined in a namespace may be explicitly declared public or internal.
They may not be explicitly declared private or protected (or protected internal) because these modifiers only make sense for members of a class.
Your protected class GetDataBL, for example, makes no sense, because "protected" means "accessible to classes that inherit from the containing class" -- but there is no containing class for GetDataBL.
private protected means they will be accessible to this class or to the derived classes.
In the Namespace level there is no class to derived from so it useless.
You can use only public or internal in the Namespace level
MSDN docs
(I believe you'll actually get a compile-time error; if you're only seeing this at execution time, then chances are your code is being compiled at execution time too, e.g. as part of a web app. Logically it's a compile-time error, not an exception.)
The protected access modifier (loosely) makes a member accessible to a derived containing type; but in the case of a namespace member there is no containing type.
Likewise a private member's accessibility domain is the program text of the containing type - and again, there is no containing type.
What are you actually trying to achieve by making GetDataBL protected?
It's the scoping of the elements that is causing the error, as explained by the error - and the C# specification (ECMA section 10.5.1):
Types declared in compilation units or namespaces can have public or internal declared accessibility and default to internal declared accessibility.
Class members can have any of the five kinds of declared accessibility and default to private declared accessibility.
Struct members can have public, internal, or private declared accessibility and default to private declared accessibility because structs are implicitly sealed.
In class Private, Protected and Protected Internal access Specifiers are not allowed at namespace level.
Only allowed Specifiers are public and internal in class.
Only to the child classes private, protected or protected internal access Specifiers are allowed .
Sample code
internal class ParentClass
{
public string test()
{
return "This is the parent class function";
}
private class BaseChildClass
{
protected string childtest()
{
return "This is the parent class function";
}
}
private class DerivedChildClass : BaseChildClass
{
private void test1()
{
string test = base.childtest();
}
}
}

Categories