Public instance of private class - never allowable in c# - c#

Apparently this works in Java:
class BigClass
{
public SecretClass not_so_secret = new SecretClass();
public class SecretClass
{
// Methods and stuff
}
}
But is there no equivalent in c#? Where I can create an instance of BigClass but NOT be allowed to create the subclass SecretClass:
class testing_class
{
BigClass BIG_CLASS_SHOULD_BE_ALLOWED = new BigClass();
BigClass.SecretClass SUB_CLASS_SHOULD_NOT = new BigClass.SecretClass();
}
I've tried combinations of internal (which sounded right...), private, protected - basically just all of them now :D
Is it a fundamental no-way-round principle in c# to always have this one-way street for access modifiers?
By the way I did find a sort-of answer here referring to Kotlin (whatever that is) and it seems to be a strict thing that just wouldn't make sense to some or be dangerous for some reason - public instances of an "internally" created private class
Is there no way to achieve that level of access in c#?

If you want to make a member (field, property, method, event, delegate or nested type) public, all the types exposed by this member must be public.
However, there is a trick on how you can make the class only instantiateable within BigClass: Make the class abstract, and if you need to write a constructor, make it protected or, since C# 7.2 private protected (see below). Then derive a nested private class from it.
public class BigClass
{
public SecretClass not_so_secret = new VerySecretClass();
public abstract class SecretClass
{
}
private class VerySecretClass : SecretClass
{
}
}
Also make everything private or protected that you don't need to expose. You can even give the setters more restrictive access modifiers.
public string Text { get; private set; } // or: protected set;
It also helps to make things internal if you are writing a class library. It makes things invisible for other assemblies.
Since C# 7.2 there is also a new level of accessibility (from C# 7 Series, Part 5: Private Protected):
Private Protected
Private Protected: The member declared with this accessibility can be visible within the types derived from this containing type within
the containing assembly. It is not visible to any types not derived
from the containing type, or outside of the containing assembly. i.e.,
the access is limited to derived types within the containing assembly.

Related

How to choose between private and protected access modifier to encapsulate members between base and childs classes?

I am trying on a project to use private values in my internal functions. In past I used only public ones, but I noticed that obfuscation is working much better when using as much as possible private parameters.
My question is regarding Parent/Child classes.
In my main class I define all the parameters as following :
public class MyFatherClass
{
private long id = -1;
public long ID { get { return this.id; } set { this.id = value; } }
...
}
So in all internal functions I access to my private value instead of the public one.
Then in my daughter class I just add parameters specific to the child class.
public class MyChildClass : MyFatherClass
{
private long anotherParameter = -1;
public long AnotherParameter { get { return this.anotherParameter; } set { this.anotherParameter = value; } }
...
}
Just, I see that in my Parent class, I can access to id and ID without problem, but from daughter classes I can only access ID(as id is private).
If I understood correct, I would need to replace all private by protected in my parent lass, so it would solve the problem?
What I don't understand is the code is working even if I leave it so.
Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?
I am now hesitating, may I just add a private id in each child class, or may I set id to protected in my parent class?
Thanks for your explanations.
Edit, just adding a screenshot of my reversed code after obfuscation, so you could understand difference on how are obfuscated private/public methods/fields
Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?
When you call a public method on a class, that method can access private members of that class:
public class Foo
{
public void Bar()
{
Baz();
}
private void Baz()
{
// private method called by public method
}
}
var foo = new Foo();
foo.Bar();
This compiles just fine. Your setter is the same: it's public, so callable from everywhere, even if it accesses private members.
As for making your field (private long id = -1;) protected: yes, that will mean you can access it in derived classes. But whether you want to is another question.
You have declared a public property for a reason. Perhaps you want to do some validation in its setter or getter. If not, if you're just using a property to access a private field, you could just ditch the entire private field and use an auto-implemented property:
public long ID { get; set; } = -1;
Then you can access the property everywhere, from within itself, from derived classes and from code using this class.
See also:
What is the difference between a field and a property?
What are Automatic Properties in C# and what is their purpose?
Here is a short and reduced description of what access modifiers do:
Public : fields (variables) and properties (variables encapsulation) and methods (functions and procedures) are visible and accessible by the class itslef, by its childs and by any other external classes.
Private : members (fields, properties and methods) are visible and accessible only by the class, not by its childs nor by any external class.
Protected : members are visible and accessible by the class and by its childs, but not by others classes.
Internal : members are visible and accessible by the class and by its childs and by any class that is in the same assembly (.exe and .dll), but not by a class from another assembly.
So you should set id to protected in the parent class to use it in the childs.
But here is the rule:
If childs classes can modify id you should set as a protected field, and offer a public property (get) if available for external items.
If childs classes are not allowed to modify it you should set it private and offer :
A propected property with only a getter if external items can't access it.
A public property with only a getter if external items can access it.
Don't repeat a member with the same name else it will hide the parent and can cause polymorphism problems, else you know what you do.
You can read these tutorials to more understand access modifier keywords:
C# Access Modifiers
Access Modifiers (C# Reference)
Here are some readings:
C# Tutorial Level 0
C# Tutorial Level 1
C# Tutorial Level 2
C# Tutorial Level 3
C# Snippets # Techi.io
Beginning Visual C# 2008 Programming
The MyChildClass class which inherits from the MyFatherClass can not access the id field because it's private. To make it accessible, you will need to change the field's access modifier to either:
protected :
////////////////////////////////////
// Dll1.dll
////////////////////////////////////
namespace Dll1
{
public class Base
{
//The field we are attempting to access
protected int a;
}
public sealed class Main : Base
{
public void DoSomething()
{
//Can be done sins Main inherits from Base
base.a = 100;
}
}
public class Invader
{
public int GetA()
{
var main = new Main();
main.DoSomething();
// can not be done sins the field is only accessible by those that inherit from Base
return main.a;
}
}
}
////////////////////////////////////
// Dll2.dll
////////////////////////////////////
namespace Dll2
{
public class ADll2Class : Dll1.Base
{
public int GetA()
{
//Can be done because ADll2Class inherits from Dll1's Base class
return base.a;
}
}
}
private protected :
Same as protected but, in the example above, Dll2's class, ADll2Class, will not be able to access the a field because it would be privately protected, in other words only classes from the same dll as Base which inherit from Base will be able to access a.
or you can set it to
internal :
If the a field in the example above was internal, then, same as private protected, Dll2's class wont be able to access it but, the Invader class in Dll1 will be able to access it sins it's part of the same dll as Base.
Note that, sins you mentioned obfuscation, try as hard as you will, the id field can still be accessed by others in an obfuscated state with the help of reflection, especially sins you provide a public property ID, might as well set everything in your project to internal.

Workaround for Multiple Inheritance in C#

I have to implement classes to transfer files to USB (class USBTransfer) and over FTP (class FTPTransfer). Since both the classes use some common methods (like getting the filename, reading some parameters etc.) so, I have implemented those methods in an another class (class FileOperations). I have inherited both the classes (i.e. class USBTransfer and class FTPTransfer) from the class FileOperations.
class FileOperations
{
protected void CommonMethod1();
protected void CommonMethod2();
}
class USBTransfer : FileOperations
{
}
class FTPTransfer : FileOperations
{
}
PROBLEM: During the file transfer operations, I set different states (not using the state machine design pattern though). I want to use a ABSTRACT class for this purpose with the following structure.
abstract class FileTransferStateMachine
{
//Public
public enum FileTransferStates { Idle = 0, FileCopyingState = 1, SuccessfullyCopiedState = 2 }
public static FileTransferStates CurrentState = FileTransferStates.Idle;
abstract protected void IdleState();
abstract protected void FileCopyingState();
abstract protected void SuccessfullyCopiedState();
}
But in C# it is not allowed to have multiple inheritance.
QUESTION: I know that I can use interface. But you cannot have variables and in that case both of my classes (i.e. class USBTransfer and class FTPTransfer) will have their own variables for the following
public enum FileTransferStates { Idle = 0, FileCopyingState = 1, SuccessfullyCopiedState = 2 }
public static FileTransferStates CurrentState = FileTransferStates.Idle;
I want to reduce redundancy and want to force to have same variables/methods (hmm...same methods can be achieved by interface) for the state machine.
Question PART-2: I can transfer files to USB or FTP as mentioned above but both the transfer operations have some common states like IdleState, FileCopyingState or SuccessfullyCopiedState which have their corresponding methods (i.e. IdleState(), FileCopyingState() or SuccessfullyCopiedState()). I want to FORCE both the classes to implement these methods (i.e. IdleState(), FileCopyingState() or SuccessfullyCopiedState()). If any class forgets to implement any method then, I should get a compiler error. Basically, the FileTransferStateMachine should be an interface/abstract class whose methods should be overridden in USBTransfer and FTPTransfer classes (which are already inheriting another class called FileOperations).
Use composition (and avoid static state members) :
abstract class FileOperations
{
protected void CommonMethod1();
protected void CommonMethod2();
protected FileTransferStateMachine Statemachine { get; set; }
}
Edit, regarding Part 2:
When you want to force the concrete classes to implement each of those methods then an interface IFileTransferStateMachine is exactly right.
You could also derive FileOperations from the StateMachine:
abstract class FileOperations: FileTransferStateMachine { }
but I would use an interface, it can be applied more granular.
Addressing both of the parts you say are a problem:
FileTransferStates can be moved out of the class, placed directly in the namespace (probably in its own file). Then it can be used by both implementations without being redefined
CurrentState can be made a non-static property (not field). Properties can be put on an interface, so they don't need an abstract class. Properties are highly recommended over fields for public members anyway, and as others have said, static isn't appropriate here.
As others have mentioned, another option is to use one of these two classes as a dependency instead of a base class. I.e. using composition instead of inheritance.

What does a public constructor on an internal class mean [duplicate]

This question already has answers here:
What's the difference between a public constructor in an internal class and an internal constructor?
(5 answers)
Closed 9 years ago.
I've seen some C# code that declares a class with an internal modifier, with a public constructor:
internal class SomeClass
{
public SomeClass()
{
}
}
What is the point of having a public constructor, if the visibility of the entire class is internal, thus it can be seen only inside the defining assembly?
Also, does this make any sense in case SomeClass is a nested class?
The internal class scope overrides the public MyClass() constructor scope, making the constructor internal.
Using public on the constructor makes it easier to update the class to public later, but confuses intent. I don't do it.
Edit 3: I missed part of your question. It is still fine to do that if your class is nested. The nesting can't make any difference, even if it is nested in a private class in a public class in a ... (see C# language specification - 3.5.2 Accessibility domains).
EDIT: And, if i recall, if the ctor is internal, it can't be used as a generic type where there is a constraint requiring where T : new(), this would require a public constructor (ref. C# language specification (version 4.0) - 4.4.3 Bound and unbound types).
Edit 2: Code sample demonstrating the above
class Program
{
internal class InternalClass {
internal InternalClass() { }
}
internal class InternalClassPublicCtor {
public InternalClassPublicCtor() { }
}
internal class GenericClass<T>
where T : new() {}
static void Main(string[] args) {
GenericClass<InternalClass> doesNotCompile = new GenericClass<InternalClass>();
GenericClass<InternalClassPublicCtor> doesCompile = new GenericClass<InternalClassPublicCtor>();
}
}
From MSDN - Access Modifiers (C# Programming Guide):
Normally, the accessibility of a member is not greater than the accessibility of the type that contains it. However, a public member of an internal class might be accessible from outside the assembly if the member implements interface methods or overrides virtual methods that are defined in a public base class.
So if, for example, you have an internal implementation of a public interface, you can still expose certain members as public.
Additionally, suppose you suddenly want your internal class to be public. It's a lot easier simply to change the access modifier on the class than all of the members.

Usage of "Class" in C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
While studying C# in ASP.net I have trouble understanding several classes. In which scenario should I use the following classes private,public,protected,abstract,static,sealed ?
It would be better if someone can explain these with easy examples.
Those are not classes.
private, protected and public are access modifiers. They indicate which other code can see the code they affect:
public class Foo
{
private int _myOwn = 1;
protected int _mineAndChildren = 2;
public int _everyOnes = 3;
}
public class Bar : Foo
{
public void Method()
{
_myOwn = 2; // Illegal - can't access private member
_mineAndChildren = 3; // Works
_everyOnes = 4; // Works
}
}
public class Unrelated
{
public void Method()
{
Foo instance = new Foo();
instance._myOwn = 2; // Illegal - can't access private member
instance._mineAndChildren = 3; // Illegal
instance._everyOnes = 4; // Works
}
}
An abstract class is one that may contain abstract members. An abstract member has no implementation, so all derived classes must implement the abstract members.
A sealed class cannot be inherited. A static class is sealed, but also can only contain static members.
I suggest you start with "Getting Started with Visual C#. This is a very basic question.
public, private and protected aren't classes, they're access modifiers. They change what is allowed to access the classes that you decorate with them. They apply to classes as well as the members of classes.
public items can be seen from anywhere
private classes can only be seen from within the same file
private members of classes can only be seen within that class
protected members are visible from within the class and its descendants
internal classes are public within the same assembly.
The abstract keyword marks a class or method as having no implementation, and it must be overridden (with the override keyword) in a derived type before you can use it.
A sealed class cannot be inherited from.
Using the static keyword on a class member indicates that the member belongs to the class itself, rather than a specific instance of it. Marking a class as static imposes the restriction that all members of this class must also be static.
private, public and protected indicate who can access members of a class. private means no one outside the class can see it. public means everyone can see it. protected is just like private, but subclasses can access it.
class Data
{
private int counter; // only accessible to class functions
protected int id; // accessible to class and subclass functions
public string name; // accessible from all code
}
abstract means this is not a finished class - it is meant to be used as a base for subclasses. Often there are virtual functions in its definition, functions intended to be "filled in" by a subclass.
abstract class Window
{
// cannot create objects of this class directly
// need to create sub class
}
static on the class definition means there's only one global copy. It pretty much reverts the class to an old-style module. static against a member indicates that it is a global member within the class, there is not a different version for every object you make of that class.
static class Configuration
{
// only one instance of the object
}
class Data
{
private static int counter; // all Data objects access this one counter
private int id; // each Data object has a different id
}
sealed prevents subclasses being created; it can also be applied to individual functions to prevent them being overridden in a subclass.
sealed class TelephoneNumber
{
// cannot create subclass of TelephoneNumber
}
class Address
{
public sealed string FormatAddress()
{
// this function cannot be overridden on a subclass
}
}
I down't can comment your question but i have an little adition but importan information for you.
access modifiers are only an compiler-feature. every .net-programm can ignore this by using reflection and can access your private flaged classes and methodes.
An exampel:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectPrivateMembers
{
class Program
{
static void Main(string[] args)
{
ConstructorInfo ci = typeof(Hello).GetConstructor(BindingFlags.NonPublic| BindingFlags.Instance ,null,System.Type.EmptyTypes,null);
object helloObject = ci.Invoke(System.Type.EmptyTypes);
MethodInfo[] helloObjectMethods = helloObject.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly| BindingFlags.Instance );
foreach (MethodInfo mi in helloObjectMethods)
{
mi.Invoke(helloObject, System.Type.EmptyTypes);
}
Console.ReadLine();
}
}
public class Hello
{
private Hello()
{
Console.WriteLine("Private Constructor");
}
public void HelloPub()
{
Console.WriteLine("Public Hello");
}
private void HelloPriv()
{
Console.WriteLine("Private Hello");
}
}
}
Source: Reflection with Private Members
The first three are access modifiers, they can be applied to types and members.
private means something can only be accessed from within its declaring type.
protected means something can be accessed by inheritors of the declaring type, or by something in the type itself.
public means something can be accessed from anywhere that has a valid reference to the declaring type.
The rest can also be applied to both types and members.
abstract (on a member) means the member has no implementation (the implementation must be provided by inheritors of the type) or (on a type) that the type cannot be instantiated (only inherited).
static (on a member) means that the member is shared statically by all callers, or (on a type) that the type can only contain static members and therefore cannot be instantiated (i.e. it doesn't have any instance members and therefore cannot serve any instances of itself).
sealed (on an inherited virtual or abstract member) means that inheritors of the type cannot override the member, or (on a type) that the type cannot be inherited from.
There are a couple of other modifiers you should be aware of:
internal is another access modifier that means that something can be accessed by anything within the same assembly (or project) as the declaring type.
Also,
virtual (on a member) means that the member may optionally be overridden by an inheritor of the type, but supplies its own default implementation.
partial (on a member) allows you to provide the signature of a member in one file, and the implementation in another, or (on a type) allows you to split the definition of a type across multiple code files.
What you have there are modifiers, not types of classes.
private, public, and protected are Access Modifiers. They define how accessible you want the code to be.
Before looking into the other modifiers you have listed, I would suggest attempting to get a grasp on Object Oriented Programming. Here is a link full of good resources you can review.
private,public,protected are the access modfier supported by c# language : here is the msdn link for more detail Access Modifiers
Abstract and Sealed Classes and Class Members
Static Classes and Static Class Members
private and public refer to the visibility of the class outside the assembly (e.g. DLL or EXE) it lives in. protected is a modifier for methods, it means only classes that inherit from the declarator can call the method.
abstract identifies a class that cannot be created directly, and is designed only to provide a base for other classes.
Applied to methods, static means they can be accessed as part of the type, rather than an instance of the class:
class Bar {
static void Foo() { ... }
void Foo() { ... }
}
The first one can be called like this:
Bar.Foo();
The second one only like this:
Bar b = new Bar();
b.Foo();
Applied to classes, static limits the class to contain only static methods. It's more aesthetic than anything else, but it also helps the compiler.
The sealed modifier tells the compiler that a class cannot be inherited from.

What is the equivalent of a 'friend' keyword in C Sharp?

What is the equivalent of a 'friend' keyword in C Sharp?
How do I use the 'internal' keyword?
I have read that 'internal' keyword is a replacement for 'friend' in C#.
I am using a DLL in my C# project that I have the source code for and yet I do not want to modify the existing code. I have inherited the class and I can use my inherited class any way I want. The problem is that most of the code in the parent class has protected methods. Will using a friend somehow make it possible to access or call these protected methods?
You can use the keyword access modifier internal to declare a type or type member as accessible to code in the same assembly only.
You can use the InternalsVisibleToAttribute class defined in System.Rutime.CompilerServices to declare a type as accessible to code in the same assembly or a specified assembly only.
You use the first as you use any other access modifier such as private. To wit:
internal class MyClass {
...
}
You use the second as follows:
[assembly:InternalsVisibleTo("MyFriendAssembly", PublicKey="...")]
internal class MyVisibleClass {
...
}
Both of these can rightly be considered the equivalent of friend in C#.
Methods that are protected are already available to derived classes.
No, "internal" is not the same as "friend" (at least the C++ 'friend')
friend specifies that this class is only accessible by ONE, particular class.
internal specifies that this class is accessible by ANY class in the assembly.
internal is the C# equivalent of the VB.NET friend keyword, as you have guessed (as opposed to a replacement)
Usage is as follows
internal void Function() {}
internal Class Classname() {}
internal int myInt;
internal int MyProperty { get; set; }
It, basically, is an access modifier that stipulates that the accessibility of the class / function / variable / property marked as internal is as if it were public to the Assembly it is compiled in, and private to any other assemblies
Your subclass will be able to access the protected members of the class you inherit.
Are you looking to give access to these protected members to another class?
Here's a weird trick I used for adding behaviour akin to C++'s friend keyword. This only works for nested classes AFAIK.
Create a nested protected or private interface with the variables you'd like to give access to via properties.
Let the nested class inherit this interface and implement it explicitly.
Whenever using an object of this nested class, cast it to the interface and call the respective properties.
Here's an example from Unity.
using System;
using UnityEngine;
using UnityEngine.Assertions;
namespace TL7.Stats
{
[CreateAssetMenu(fileName = "Progression", menuName = "TL7/Stats/New Progression", order = 0)]
public class Progression : ScriptableObject
{
// Provides access to private members only to outer class Progression
protected interface IProgressionClassAccess
{
CharacterClass CharacterClass { get; set; }
}
[System.Serializable]
public struct ProgressionClass : IProgressionClassAccess
{
[Header("DO NOT EDIT THIS VALUE.")]
[SerializeField] private CharacterClass characterClass;
[Tooltip("Levels are 0 indexed.")]
[SerializeField] float[] healthOverLevels;
public float[] HealthOverLevels => healthOverLevels;
CharacterClass IProgressionClassAccess.CharacterClass
{
get => characterClass;
set => characterClass = value;
}
}
static readonly Array characterClasses = Enum.GetValues(typeof(CharacterClass));
[SerializeField] ProgressionClass[] classes = new ProgressionClass[characterClasses.Length];
public ProgressionClass this[in CharacterClass index] => classes[(int)index];
void Awake()
{
for (int i = 0; i < classes.Length; ++i)
{
// Needs to be cast to obtain access
(classes[i] as IProgressionClassAccess).CharacterClass = (CharacterClass)characterClasses.GetValue(i);
}
}
#if UNITY_EDITOR
public void AssertCorrectSetup()
{
for (int i = 0; i < characterClasses.Length; ++i)
{
CharacterClass characterClass = (CharacterClass)characterClasses.GetValue(i);
Assert.IsTrue(
(this[characterClass] as IProgressionClassAccess).CharacterClass == characterClass,
$"You messed with the class values in {GetType()} '{name}'. This won't do."
);
}
}
#endif
}
}
I think this only works for nested classes. In case you want to do this with regular classes, you'd need to nest them inside a partial outer class, which should work in theory, and use a protected or private nested interface (or two, if you're inclined) for providing them access to each other's privates... that came out wrong.
Internal is the equivalent of friend. A protected method is only available within the same class or from an inheritor. If you're trying to expose protected methods from an inheritor, you can wrap them in public methods.
Splitting a big class in two partial class-files can achive the desired friend-effect. It is not equivalent, but it works in some cases.

Categories