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 3 years ago.
Improve this question
I'm new to C#.Till this moment I used to make every global variable - public static.All my methods are public static so I can access them from other classes.
I read on SO that the less public static methods I have,the better.So I rewrote my applications by putting all the code in one class - the form class.Now all my methods are private and there's no static method.
My question: What should I do,keeping everything in the form class is dump in my opinion.
When should I use public,when private and when static private/public?
I get the public methods as a 'cons' ,because they can be decompiled,but I doubt that.My public methods can be decompiled too.What is so 'private' in a private method?
EDIT: I'm not asking how to prevent my program to be decompiled,I'm asking whether I should use static,private and public.And also : Is there are problem in putting all the code in the form class so I dont have to use public methods?
Everything should be private unless proven otherwise.
The difference between public and private is between what is supposed to be kept compatible and what is not supposed to be kept compatible, what is supposed to be interesting to the world and what is not supposed to be its business.
When you declare something public, the class (and consequently the object) is making a strong statement: this is my visible interface, there are many other like this, but this is mine.
The public interface is a contractual agreement that your class is exporting to the rest of the world (whatever that means) about what it can do. If you modify the public interface, you risk breaking the contract that the rest of the world is assuming about the class.
On the other hand, private stuff is internal to the class. It supports functionality that the class must use to do its job while carrying the object state around (if it's a method) or keeping its internal state (if it's a variable). You are free to hack and tinker the class private stuff as much as you want, without breaking the interface contract, meaning that this gives you wide freedom for refactoring (of the internal data representation, for example, for efficiency). Private stuff is not part of the interface.
Protected is something that involves the openness to reimplementation. Avoid, if you can, deeply nested inheritances. You risk making things very difficult to handle, as your reimplementation class can screw the base class.
Technically, a class should declare an interface (public) and an implementation (private). The interface should not have code at all, just delegate to the private "implementation" logic. This is why in Java and C# you have interface statement, which formalizes the pure abstract class concept in C++.
Static is something that resides logically in the realm of your class but does not depend on the state of the class itself. It should be used sparingly when a design pattern dictates it (e.g., singleton, factory method).
private is for class members that you want only access within the class of the body, and in C# members are default set to private unless specified different
examples of when to use private:
class Account
{
private int pin = 1090;
public int Pin
{
get { return pin; }
}
}
public on the other hand is the opposite, there are no restrictions with accessing public members, so when things that don't matter with the user having access to should be public.
static on the other hand has no relation to the two, because it doesn't deal with permission to methods, static on the other hand is a constant or type declaration. If the word static is applied to the class then every member in the class must be declared static.
examples of when to use static:
static int birth_year= 1985
Modifiers in C# Reference will give you more detail of all modifiers in C# and examples of how they should be used
All is answered above already, but I think it could be simplified a bit... so decorate a method public, if other classes will be using this method. If not - mark it private.
For instance you have Class A and Class B. Say Class A has 3 methods (x,y,z). Methods x, y will be used by Class B, so mark them both public, but method z will be only be used by method x inside Class A so mark it private as there's no need to be exposing this method to the external world. The logic inside this method is intended for internal use only.
Static is differentl this decoration means you cannnot create an instance of an object marked static. The object is - as the keyword says - static (cannot be changed or modified).
See Access Modifiers (C# Programming Guide). But it's be far better if you got yourself a decent C# and OOP/OOD book: these are really basics of computer science.
Long story short: access modifiers promote encapsulation, which basically means that every class should keep its privates to itself.
This seems more basic than the question linked above. To properly thrive in an OO language, you'll need to figure out how to decompose your end goal into a series of objects that work together (even containing and extending one another) to achieve a series of goals. This abstraction has numerous benefits which become apparent once you begin properly implementing OO design. You're going to want a new C# book, as mentioned, if you haven't already gotten to the part explaining the basics of Object Oriented Programming.
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Here is an example:
public class Bicycle {
private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;
public Bicycle(int startCadence, int startSpeed, int startGear){
gear = startGear;
cadence = startCadence;
speed = startSpeed;
id = ++numberOfBicycles;
}
// new method to return the ID instance variable
public int getID() {
return id;
}
...
}
In addition to the above, think about working scenario. You are not working alone. Your peer fellow might call the methods from your class which you actually don't want to expose, or think it needs critical changes in the future. That might be the case you want a private
Related
A little background: I'm new to C# and Unity, but catching on very quickly. I'm also hoping this thread will not spark a debate about the merits of classes and abstract coding, as that debate is unrelated and well-worn (and unnecessarily heated); so please keep that in mind.
I'm simply wondering if every C# script in Unity is required to have a main class in any way or for any reason.
Or instead, can methods, and variables can be written outside of a class in a blank file (with namespaces) to be used in a video game?
I'm asking because, when I create a new C# script, it seems to force a class into my file and I'm afraid of breaking things.
I hope to keep code abstraction to a minimum, and the current project
I'm working on has several situations where a class is not needed, or
only one instance of the class will be used. I'd like to simply avoid
using classes in those cases.
In terms of declaring/defining variables and methods outside of any class, you can't really do that in C#. It just isn't how the language was designed (the answers to the question I linked to expand on that idea, so I won't duplicate them here).
You're not without options, though; if you have a number of variables or methods that need to be accessible from different places and don't need an object reference, you can make them static, so you won't need to instantiate the class to make use of them:
public class UtilityClass
{
public static float GravityConstant = 3.51f;
public static string GameName = "MyFirstGame";
public static float CalculateProduct(float a, float b)
{
return a * b;
}
}
Then, you can reference the class's methods/members by accessing it through its name:
float product = UtilityClass.CalculateProduct(6, 1.5f);
An example of where you might use this pattern is when defining mathematical formulae which aren't included in Unity's Mathf methods, and using them in multiple classes.
Additional note: Creating a new C# script through Unity's editor UI will default to declaring a class of the same name that inherits from Monobehaviour. You can alter it to remove the inheritance from Monobehaviour if you don't need any of the methods/attributes of the class, which avoids unnecessary overhead. One example for this would be with a static class that you never need to instantiate.
Yes, you are.
In C#, things like global variables and functions just do not exist. Everything must be contained in a class.
"But what should I do in order to declare some stuff that can be accessed everywhere, without creating an object?" you asked. There is something called the static modifier. You can access the methods or variables or fields or properties marked with this modifier without creating an object of that class.
You just add the word static in a method and it becomes a static method! How simple!
Let's see an example.
I have this non-static method:
public class MyClass {
public void DoStuff () {
}
}
I can call it like this:
var obj = new MyClass();
obj.DoStuff();
But if I modify it with static,
public class MyClass {
public static void DoStuff () {
}
}
I can call it like this:
MyClass.DoStuff();
How convenient!
Note:
Please do not misuse the static modifier! Only use it when it makes sense! When? When the method is a utility method or when the method does not belong to individual objects but the class itself.
First of All you need to check where Methods define as offical
docs stated
"Methods are declared in a class or struct by specifying the access
level such as public or private...."
So, Method should be declare in a Class or struct and A given class
should be, ideally, responsible for just one task.(see also)
Your this question "Or instead, can methods, and variables can be
written outside of a class in a blank file (with namespaces) to be
used in a video game?" answer is hidden in the below question.
Can there be stand alone functions in C# without a Class?
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
You have to make a class in order to use methods or its variable
either instance class or static class.
Am I required to use Classes for every script? Every script means you required a class. Unity Support Component Based
Architectural Design and if you require any script related
work then you definitely require a script component which means a
class require.
Finally for singleton, thanks to Unity3dWiki great detail
available. I think you will be feel comfortable to code and writing
class if you keep in mind component based architecture of Unity3d.
Singleton vs Static: I will also recommend to check this: Why do you use a Singleton class
if a Static class serves the purpose
Hope it will help.
[Note: If this helpful Any one can update this answer for future reference and use].
I am developing C# and asp.net web application.
I have general class called utilities, I have lot of public and static variables in this public utilities class.
Since this number is gradually increasing, I want to know is it good practice to store utilities methods and variable as public static.
Example of my code
public class utilities
{
public static string utilVariable1 = "Myvalue";
public static string utilVariable2 = "Myvalue";
public static string utilVariable3 = "Myvalue";
:
public static string utilVariableN = "Myvalue";
public static string UtilMethod1()
{
//do something
}
public static string UtilMethod2()
{
//do something
}
public static string UtilMethodN()
{
//do something
}
}
There's nothing inherently wrong with static classes, although they should typically not have state (fields). Your use of public static fields indicates that this is not the case, so it seems like you are using abusing the static keyword slightly. If your class needs to have state, then it should be a normal, non-static class, and you should create instances of it. Otherwise, the only public fields visible on the class should be const (consider the Math class, with constants such as Math.PI - a good use of static methods and fields).
Another consideration is cohesion. Methods typically exist grouped in one class because they are closely related in one way or another. Again, the Math class is a good example; everything in there has to do with maths. At some point, you would want to split your global utility class into multiple smaller, more focussed ones. See Wikipedia for some examples on cohesion, it sounds like your usage falls under "Coincidental cohesion (worst)".
There's nothing wrong with this approach for methods, but variables should really be const if they're going to be static and public. If they are subject to change then you should look at a different structure for variables that are being manipulated by more than one component.
Personally, I'm a fan of the Singleton pattern.
static is not a bad thing per se. Methods that don't need to access any member variables or methods should always be declared static. That way the reader of the code sees immediately that a method won't change member variables or methods.
For variables the situation is different, you should avoid static variables unless you make them const. Public static variables are globally accessible and can easily raise issues if multiple threads access the same variable without proper synchronization.
It is hard to tell for your case if it's a good or a bad idea to use statics, because you didn't provide any context information.
Creating one class to do it all is not a good practice, and it's recommended to structure your project, and keep stuff that belongs to each other separated from the randomness.
A great example of this was a project I took over from a co-worker. There was 1 class, called Methods. It contained over 10K lines of methods.
I then categorized them into approx. 20 files, and the structure was restored.
Most of the methods from that project were validating user input, which can easily be moved into a static class Validation.
One awful thing I notice is the mutable public and static variables. This is bad for several reasons:
Incorrect behavior, because if some method changes this, while it isn't supposed to do that, it causes other methods to behave improperly, and it's really hard to track down/debug.
Concurrency, how are we going to ensure thread safety? Do we let it over to all methods that work with that? Say if it's a value type, what will we let them lock on? What if some method forgets to make it thread safe?
Expand-ability (I hope you understand what I mean with that), if you have for example a static class data that stores all these public static variables, that you shouldn't have. It can store that once, if for example you might change your application structure a bit, and say want to make it possible to load two projects in the same screen, then it's very difficult to make that possible, because you can't create two instances of a static class. There is only one class, and it'll remain like that.
For number 3 a cleaner solution would be to store either a list of instances of a data class, or to store a reference to the default and/or active data class.
Static member, and private static members (or protected) are a good practice, as long as you don't make huge classes, and the methods are related.
Public and static variables are okay if they're not really variable.
The two ways to do this is by marking them constant (const modifier) or readonly (readonly modifier).
Example:
public class UtilitiesClass
{
internal UtilitiesClass() { }
public void UtilityMethod1()
{
// Do something
}
}
// Method 1 (readonly):
public static readonly UtilitiesClass Utilities = new UtilitiesClass();
// Method 2 (property):
private static UtilitiesClass _utilities = new UtilitiesClass();
public static UtilitiesClass Utilities
{
get { return _utilities; }
private set { _utilities = value; }
}
The advantage of method 1 is that you don't have to worry about thread-safety at all, the value can't change.
Method 2 is not thread-safe (though it's not difficult to make it that), but it has the advantage of allowing the static class itself to change the reference to the utilities class.
No, it is not a good practice for large applications, especially not if your static variables are mutable, as they are then effectively global variables, a code smell which Object Oriented Programming was supposed to "solve".
At the very least start by grouping your methods into smaller classes with associated functionality - the Util name indicates nothing about the purpose of your methods and smells of an incoherent class in itself.
Second, you should always consider if a method is better implemented as a (non-static) method on the same object where the data that is passed as argument(s) to the method lives.
Finally, if your application is quite large and/or complex, you can consider solutions such as an Inversion of Control container, which can reduce the dependency on global state. However, ASP.Net webforms is notoriously hard to integrate into such an environment, as the framework is very tightly coupled in itself.
I am fairly new to C# programming so this is likely a beginner's question.
I get a "'A.Test.That.Fails' is inaccessible due to its protection level" error on the following code snippet and I fail to understand the reason.
namespace A
{
class Test
{
public void Demo()
{
That[] it = new That[42];
it[0].fails = 21;
}
public struct That
{
int fails;
}
}
}
Coming from C++ programming and having read that protection rules are almost the same, since there is a single class I would expect it to work even if both the That struct and the Demo method were private.
As the side note, a link to some page summing up scope and protection rules toward the C++ programmer would be greatly appreciated.
The other answers given already have your answer, so I won't beat a dead horse here. You need to declare the field public in order to be able to access it from external code.
In C++, structs and classes are equivalent, with the only difference being the default access level of their respective members.
However, that's not the case in C#. Generally, you should only use a struct for small, short-lived objects that are immutable (won't change). A structure has value type semantics, where as a class has reference type semantics. It's very important that you understand the difference between value types and reference types if you're learning to program in C#. Jon Skeet has published an article that attempts to provide that explanation. But you'll definitely want to pick up a good introductory book to C# that treats these issues in more detail.
More often than not, you'll want to use a class in C#, rather than a structure. And when you use that class, note that Microsoft's design guidelines for C# tend to recommend against exposing public fields. Instead, they recommend that you use a public property, backed by a private field. A more thorough exposition of the rationale behind that guideline is given here. For example:
class TimePeriod
{
private double seconds;
public double Seconds
{
get { return seconds; }
set { seconds = value; }
}
}
Or you can use the simpler "automatic properties" syntax, which has the compiler automatically generate that private backing field:
class TimePeriod
{
public double Seconds { get; set; }
}
The default access modifier in C# for struct fields (and class fields) is private. So int fails; is private to your struct, unless you declare it public.
please see the answer to this question
That member is being declared private by default - you need to put the public modifier before it.
Because fails is not public.. by default fields in struct and even class are private
According to MSDN
The access level for class members and struct members, including nested classes and structs, is private by default.
Private members of Test restrict to Test itself and are not available outside of Test. Demo is outside of Test. It doesn't matter who the parent is.
Define Demo inside Test and you can access the private members.
We have a Student class in our business model. something struck me as strange, if we are manipulating one student from another student, the students private members are visible, why is this?
class Program {
static void Main(string[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.SeePrivatePropertiesAndFields(s2);
}
}
public class Student {
private String _studentsPrivateField;
public Student() {
_studentsPrivateField = DateTime.Now.Ticks.ToString();
}
public void SeePrivatePropertiesAndFields(Student anotherStudent) {
//this seems like these should be private, even from the same class as it is a different instantiation
Console.WriteLine(anotherStudent._studentsPrivateField);
}
}
Can i have some thoughts on the design considerations/implications of this. It seems that you can't hide information from your siblings. Is there a way to mark a field or member as hidden from other instances of the same class?
There's an easy way to ensure this:
Don't mess around with private members of other instances of the same class.
Seriously - you're the one writing the Student code.
The easiest way to ensure this is to program to an interface, such as:
class Program
{
static void Main(string[] args)
{
IStudent s1 = new Student();
IStudent s2 = new Student();
s1.ExamineStudentsMembers(s1);
}
}
public interface IStudent
{
void ExamineStudentsMembers(IStudent anotherStudent);
}
public class Student : IStudent
{
private string _studentsPrivateMember;
public Student()
{
_studentsPrivateMember = DateTime.Now.Ticks.ToString();
}
public void ExamineStudentsMembers(IStudent anotherStudent)
{
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
}
This will no longer compile due to ExamineStudentsMembers trying to access a private field.
If you are writing the class, you have complete control over it, so if you don't want one object to be able to modify another, don't write in that functionality.
Classes will often use private variables in other instances to implement efficient comparison and copy functions.
Private just means that the member (field/method/etc.) can be accessed only from the within the code of the parent type. From CSharpOnline
Private members of multiple instances are visible and can be invoked. This comes in handy when you are implementing a "copy constructor" or a "clone" method on your type, where the argument is an instance of the same type. If the designers would have made private fields inaccessible, then you may have to create a bunch of getter methods just for clone/copy to get at them. IMHO, I like it better the way it is. Within the same type, Reading another object's state isn't that bad as writing to it though (which could be a DONT-code-convention for you/your team.)
Accessing a sibling's private data may seem wrong when phrased like:
public void ExamineStudentsMembers(Student anotherStudent) {
//this seems very wrong
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
However, it doesn't seem so odd for methods which require this sort of functionality. What methods require accessing a sibling's private data? Comparison methods (in particular equals) and objects in a data structure (say a tree or linked list).
Comparison methods often compare private data directly rather than just the public data.
For a class of nodes that make up a linked list, graph or tree, being able to access a sibling's private data is exactly what is needed. Code in the know (part of the class) can tinker around with the data structure, but code outside of the data structure cannot touch the internals.
It is interesting to note that these two cases are less common in day-to-day programming than when this language feature were first developed. Back in 1990s and early 2000s, in C++ it would have been much more common to build custom data structures and comparison methods. Perhaps it is a good time to reconsider private members.
i like the second point, you can look, but dont touch those private members.
it's funny you should say that, i knew a teacher once and he said he often had a problem deciding what classes it was ok to look at the members and which ones he could actually have a play with.
An object is just a piece of data; the class contains the functionality. A member method is just a nice trick the compiler plays; it's really more like a static method with an implied argument (sort of like extension methods). With that in mind, protecting objects from each other doesn't make any sense; you can only protect classes from each other. So it's natural that it works that way.
No, this is necessary, the method code is not specific to the instance, it is only specific to the type of the object. (virtual methods) or the declared type of the variable (for non-virtual methods). The non-static fields, on the other hand, are instance specific... That's where you have instance-level isolation.
The only difference between a static method and a non-static method is that the static method is not allowed to access other instance based (non-static) methods or fields. Any method that CAN be made static without modification will not be affected in any way by making it static, except to force compiler to throw errors anywhere it was called using instance-based syntax.
If you intend to examine a given student's information then I would change the method to be static:
public static void ExamineStudentsMembers(Student student)
{
Console.WriteLine(student._studentsPrivateMember);
}
You would then use Student.ExamineStudentsMembers(s1). Using s1.ExamineStudentsMembers(s2) would be invalid.
If this isn't the intended purpose I would rewrite the method as:
public void ExamineStudentsMembers()
{
Console.WriteLine(_studentsPrivateMember);
}
The above would then be used by writing s1.ExamineStudentsMembers()
Private members are to hide implementation details from clients. The clients should only see the interface (public methods / fields / properties).
The purpose is not to protect the programmer from himself.
This is also NOT a security feature because you can always access private fields via reflection.
It's really to separate interface & implementation (black box design), and clients programming against a contract (all public fields).
For example if you have a public get property, it could access some private field directly, or it could calculate the value from some other fields.
The purpose is, the client only knows the contract (the public property) and the implementation can be changed without affecting the client
Object scope does not ever imply security - ever! It is role of the OS to provide runtime security. It is a bug to design a system that relies on language specific object scope to limit runtime object instance data access. If this were not the case, then all non OO languages are, by definition, not secure.
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 5 years ago.
Improve this question
The C++ friend keyword allows a class A to designate class B as its friend. This allows Class B to access the private/protected members of class A.
I've never read anything as to why this was left out of C# (and VB.NET). Most answers to this earlier StackOverflow question seem to be saying it is a useful part of C++ and there are good reasons to use it. In my experience I'd have to agree.
Another question seems to me to be really asking how to do something similar to friend in a C# application. While the answers generally revolve around nested classes, it doesn't seem quite as elegant as using the friend keyword.
The original Design Patterns book uses it regularly throughout its examples.
So in summary, why is friend missing from C#, and what is the "best practice" way (or ways) of simulating it in C#?
(By the way, the internal keyword is not the same thing, it allows all classes within the entire assembly to access internal members, while friend allows you to give a certain class complete access to exactly one other class)
On a side note.
Using friend is not about violating the encapsulation, but on the contrary it's about enforcing it. Like accessors+mutators, operators overloading, public inheritance, downcasting, etc., it's often misused, but it does not mean the keyword has no, or worse, a bad purpose.
See Konrad Rudolph's message in the other thread, or if you prefer see the relevant entry in the C++ FAQ.
Having friends in programming is more-or-less considered "dirty" and easy to abuse. It breaks the relationships between classes and undermines some fundamental attributes of an OO language.
That being said, it is a nice feature and I've used it plenty of times myself in C++; and would like to use it in C# too. But I bet because of C#'s "pure" OOness (compared to C++'s pseudo OOness) MS decided that because Java has no friend keyword C# shouldn't either (just kidding ;))
On a serious note: internal is not as good as friend but it does get the job done. Remember that it is rare that you will be distributing your code to 3rd party developers not through a DLL; so as long as you and your team know about the internal classes and their use you should be fine.
EDIT Let me clarify how the friend keyword undermines OOP.
Private and protected variables and methods are perhaps one of the most important part of OOP. The idea that objects can hold data or logic that only they can use allows you to write your implementation of functionality independent of your environment - and that your environment cannot alter state information that it is not suited to handle. By using friend you are coupling two classes' implementations together - which is much worse then if you just coupled their interface.
For info, another related-but-not-quite-the-same thing in .NET is [InternalsVisibleTo], which lets an assembly designate another assembly (such as a unit test assembly) that (effectively) has "internal" access to types/members in the original assembly.
In fact, C# gives possibility to get same behavior in pure OOP way without special words - it's private interfaces.
As far as question What is the C# equivalent of friend? was marked as duplicate to this article and no one there propose really good realization - I will show answer on both question here.
Main idea was taking from here: What is a private interface?
Let's say, we need some class which could manage instances of another classes and call some special methods on them. We don't want to give possibility to call this methods to any other classes. This is exactly same thing what friend c++ keyword do in c++ world.
I think good example in real practice could be Full State Machine pattern where some controller update current state object and switch to another state object when necessary.
You could:
The easiest and worst way to make Update() method public - hope
everyone understand why it's bad.
Next way is to mark it as internal. It's good enough if you put your
classes to another assembly but even then each class in that assembly
could call each internal method.
Use private/protected interface - and I followed this way.
Controller.cs
public class Controller
{
private interface IState
{
void Update();
}
public class StateBase : IState
{
void IState.Update() { }
}
public Controller()
{
//it's only way call Update is to cast obj to IState
IState obj = new StateBase();
obj.Update();
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
//it's impossible to write Controller.IState p = new Controller.StateBase();
//Controller.IState is hidden
var p = new Controller.StateBase();
//p.Update(); //is not accessible
}
}
Well, what about inheritance?
We need to use technique described in Since explicit interface member implementations cannot be declared virtual and mark IState as protected to give possibility to derive from Controller too.
Controller.cs
public class Controller
{
protected interface IState
{
void Update();
}
public class StateBase : IState
{
void IState.Update() { OnUpdate(); }
protected virtual void OnUpdate()
{
Console.WriteLine("StateBase.OnUpdate()");
}
}
public Controller()
{
IState obj = new PlayerIdleState();
obj.Update();
}
}
PlayerIdleState.cs
public class PlayerIdleState: Controller.StateBase
{
protected override void OnUpdate()
{
base.OnUpdate();
Console.WriteLine("PlayerIdleState.OnUpdate()");
}
}
And finally example how to test class Controller throw inheritance:
ControllerTest.cs
class ControllerTest: Controller
{
public ControllerTest()
{
IState testObj = new PlayerIdleState();
testObj.Update();
}
}
Hope I cover all cases and my answer was useful.
You should be able to accomplish the same sorts of things that "friend" is used for in C++ by using interfaces in C#. It requires you to explicitly define which members are being passed between the two classes, which is extra work but may also make the code easier to understand.
If somebody has an example of a reasonable use of "friend" that cannot be simulated using interfaces, please share it! I'd like to better understand the differences between C++ and C#.
With friend a C++ designer has precise control over whom the private* members are exposed to. But, he's forced to expose every one of the private members.
With internal a C# designer has precise control over the set of private members he’s exposing. Obviously, he can expose just a single private member. But, it will get exposed to all classes in the assembly.
Typically, a designer desires to expose only a few private methods to selected few other classes. For example, in a class factory pattern it may be desired that class C1 is instantiated only by class factory CF1. Therefore class C1 may have a protected constructor and a friend class factory CF1.
As you can see, we have 2 dimensions along which encapsulation can be breached. friend breaches it along one dimension, internal does it along the other. Which one is a worse breach in the encapsulation concept? Hard to say. But it would be nice to have both friend and internal available. Furthermore, a good addition to these two would be the 3rd type of keyword, which would be used on member-by-member basis (like internal) and specifies the target class (like friend).
* For brevity I will use "private" instead of "private and/or protected".
- Nick
You can get close to C++ "friend" with the C# keyword "internal".
Friend is extremely useful when writing unit test.
Whilst that comes at a cost of polluting your class declaration slightly, it's also a compiler-enforced reminder of what tests actually might care about the internal state of the class.
A very useful and clean idiom I've found is when I have factory classes, making them friends of the items they create which have a protected constructor. More specifically, this was when I had a single factory responsible for creating matching rendering objects for report writer objects, rendering to a given environment. In this case you have a single point of knowledge about the relationship between the report-writer classes (things like picture blocks, layout bands, page headers etc.) and their matching rendering objects.
C# is missing the "friend" keyword for the same reason its missing deterministic destruction. Changing conventions makes people feel smart, as if their new ways are superior to someone else' old ways. It's all about pride.
Saying that "friend classes are bad" is as short-sighted as other unqualified statements like "don't use gotos" or "Linux is better than Windows".
The "friend" keyword combined with a proxy class is a great way to only expose certain parts of a class to specific other class(es). A proxy class can act as a trusted barrier against all other classes. "public" doesn't allow any such targeting, and using "protected" to get the effect with inheritance is awkward if there really is no conceptual "is a" relationship.
This is actually not an issue with C#. It's a fundamental limitation in IL. C# is limited by this, as is any other .Net language that seeks to be verifiable. This limitation also includes managed classes defined in C++/CLI (Spec section 20.5).
That being said I think that Nelson has a good explanation as to why this is a bad thing.
Stop making excuses for this limitation. friend is bad, but internal is good? they are the same thing, only that friend gives you more precise control over who is allowed to access and who isn't.
This is to enforce the encapsulation paradigm? so you have to write accessor methods and now what? how are you supposed to stop everyone (except the methods of class B) from calling these methods? you can't, because you can't control this either, because of missing "friend".
No programming language is perfect. C# is one of the best languages I've seen, but making silly excuses for missing features doesn't help anyone. In C++, I miss the easy event/delegate system, reflection (+automatic de/serialization) and foreach, but in C# I miss operator overloading (yeah, keep telling me that you didn't need it), default parameters, a const that cannot be circumvented, multiple inheritance (yeah, keep telling me that you didn't need it and interfaces were a sufficient replacement) and the ability to decide to delete an instance from memory (no, this is not horribly bad unless you are a tinkerer)
I will answer only "How" question.
There are so many answers here, however I would like to propose kind of "design pattern" to achieve that feature. I will use simple language mechanism, which includes:
Interfaces
Nested class
For example we have 2 main classes: Student and University. Student has GPA which only university allowed to access. Here is the code:
public interface IStudentFriend
{
Student Stu { get; set; }
double GetGPS();
}
public class Student
{
// this is private member that I expose to friend only
double GPS { get; set; }
public string Name { get; set; }
PrivateData privateData;
public Student(string name, double gps) => (GPS, Name, privateData) = (gps, name, new PrivateData(this);
// No one can instantiate this class, but Student
// Calling it is possible via the IStudentFriend interface
class PrivateData : IStudentFriend
{
public Student Stu { get; set; }
public PrivateData(Student stu) => Stu = stu;
public double GetGPS() => Stu.GPS;
}
// This is how I "mark" who is Students "friend"
public void RegisterFriend(University friend) => friend.Register(privateData);
}
public class University
{
var studentsFriends = new List<IStudentFriend>();
public void Register(IStudentFriend friendMethod) => studentsFriends.Add(friendMethod);
public void PrintAllStudentsGPS()
{
foreach (var stu in studentsFriends)
Console.WriteLine($"{stu.Stu.Name}: stu.GetGPS()");
}
}
public static void Main(string[] args)
{
var Technion = new University();
var Alex = new Student("Alex", 98);
var Jo = new Student("Jo", 91);
Alex.RegisterFriend(Technion);
Jo.RegisterFriend(Technion);
Technion.PrintAllStudentsGPS();
Console.ReadLine();
}
There is the InternalsVisibleToAttribute since .Net 3 but I suspect they only added it to cater to test assemblies after the rise of unit testing. I can't see many other reasons to use it.
It works at the assembly level but it does the job where internal doesn't; that is, where you want to distribute an assembly but want another non-distributed assembly to have privileged access to it.
Quite rightly they require the friend assembly to be strong keyed to avoid someone creating a pretend friend alongside your protected assembly.
I have read many smart comments about "friend" keyword & i agree what it is useful thing, but i think what "internal" keyword is less useful, & they both still bad for pure OO programming.
What we have? (saying about "friend" I also saying about "internal")
is using "friend" makes code less pure regarding to oo?
yes;
is not using "friend" makes code better?
no, we still need to make some private relationships between classes, & we can do it only if we break our beautiful encapsulation, so it also isn`t good, i can say what it even more evil than using "friend".
Using friend makes some local problems, not using it makes problems for code-library-users.
the common good solution for programming language i see like this:
// c++ style
class Foo {
public_for Bar:
void addBar(Bar *bar) { }
public:
private:
protected:
};
// c#
class Foo {
public_for Bar void addBar(Bar bar) { }
}
What do you think about it? I think it the most common & pure object-oriented solution. You can open access any method you choose to any class you want.
I suspect it has something to do with the C# compilation model -- building IL the JIT compiling that at runtime. i.e.: the same reason that C# generics are fundamentally different to C++ generics.
you can keep it private and use reflection to call functions. Test framework can do this if you ask it to test a private function
I used to regularly use friend, and I don't think it's any violation of OOP or a sign of any design flaw. There are several places where it is the most efficient means to the proper end with the least amount of code.
One concrete example is when creating interface assemblies that provide a communications interface to some other software. Generally there are a few heavyweight classes that handle the complexity of the protocol and peer peculiarities, and provide a relatively simple connect/read/write/forward/disconnect model involving passing messages and notifications between the client app and the assembly. Those messages / notifications need to be wrapped in classes. The attributes generally need to be manipulated by the protocol software as it is their creator, but a lot of stuff has to remain read-only to the outside world.
It's just plain silly to declare that it's a violation of OOP for the protocol / "creator" class to have intimate access to all of the created classes -- the creator class has had to bit munge every bit of data on the way up. What I've found most important is to minimize all the BS extra lines of code the "OOP for OOP's Sake" model usually leads to. Extra spaghetti just makes more bugs.
Do people know that you can apply the internal keyword at the attribute, property, and method level? It's not just for the top level class declaration (though most examples seem to show that.)
If you have a C++ class that uses the friend keyword, and want to emulate that in a C# class:
1. declare the C# class public
2. declare all the attributes/properties/methods that are protected in C++ and thus accessible to friends as internal in C#
3. create read only properties for public access to all internal attributes and properties
I agree it's not 100% the same as friend, and unit test is a very valuable example of the need of something like friend (as is protocol analyzer logging code). However internal provides the exposure to the classes you want to have exposure, and [InternalVisibleTo()] handles the rest -- seems like it was born specifically for unit test.
As far as friend "being better because you can explicitely control which classes have access" -- what in heck are a bunch of suspect evil classes doing in the same assembly in the first place? Partition your assemblies!
The friendship may be simulated by separating interfaces and implementations. The idea is: "Require a concrete instance but restrict construction access of that instance".
For example
interface IFriend { }
class Friend : IFriend
{
public static IFriend New() { return new Friend(); }
private Friend() { }
private void CallTheBody()
{
var body = new Body();
body.ItsMeYourFriend(this);
}
}
class Body
{
public void ItsMeYourFriend(Friend onlyAccess) { }
}
In spite of the fact that ItsMeYourFriend() is public only Friend class can access it, since no one else can possibly get a concrete instance of the Friend class. It has a private constructor, while the factory New() method returns an interface.
See my article Friends and internal interface members at no cost with coding to interfaces for details.
Some have suggested that things can get out of control by using friend. I would agree, but that doesn't lessen its usefulness. I'm not certain that friend necessarily hurts the OO paradigm any more than making all your class members public. Certainly the language will allow you to make all your members public, but it is a disciplined programmer that avoids that type of design pattern. Likewise a disciplined programmer would reserve the use of friend for specific cases where it makes sense. I feel internal exposes too much in some cases. Why expose a class or method to everything in the assembly?
I have an ASP.NET page that inherits my own base page, that in turn inherits System.Web.UI.Page. In this page, I have some code that handles end-user error reporting for the application in a protected method
ReportError("Uh Oh!");
Now, I have a user control that is contained in the page. I want the user control to be able to call the error reporting methods in the page.
MyBasePage bp = Page as MyBasePage;
bp.ReportError("Uh Oh");
It can't do that if the ReportError method is protected. I can make it internal, but it is exposed to any code in the assembly. I just want it exposed to the UI elements that are part of the current page (including child controls). More specifically, I want my base control class to define the exact same error reporting methods, and simply call methods in the base page.
protected void ReportError(string str) {
MyBasePage bp = Page as MyBasePage;
bp.ReportError(str);
}
I believe that something like friend could be useful and implemented in the language without making the language less "OO" like, perhaps as attributes, so that you can have classes or methods be friends to specific classes or methods, allowing the developer to provide very specific access. Perhaps something like...(pseudo code)
[Friend(B)]
class A {
AMethod() { }
[Friend(C)]
ACMethod() { }
}
class B {
BMethod() { A.AMethod() }
}
class C {
CMethod() { A.ACMethod() }
}
In the case of my previous example perhaps have something like the following (one can argue semantics, but I'm just trying to get the idea across):
class BasePage {
[Friend(BaseControl.ReportError(string)]
protected void ReportError(string str) { }
}
class BaseControl {
protected void ReportError(string str) {
MyBasePage bp = Page as MyBasePage;
bp.ReportError(str);
}
}
As I see it, the friend concept has no more risk to it than making things public, or creating public methods or properties to access members. If anything friend allows another level of granularity in accessibility of data and allows you to narrow that accessibility rather than broadening it with internal or public.
If you are working with C++ and you find your self using friend keyword, it is a very strong indication, that you have a design issue, because why the heck a class needs to access the private members of other class??
B.s.d.
It was stated that, friends hurts pure OOness. Which I agree.
It was also stated that friends help encapsulation, which I also agree.
I think friendship should be added to the OO methodology, but not quite as it in C++. I'd like to have some fields/methods that my friend class can access, but I'd NOT like them to access ALL my fields/methods. As in real life, I'd let my friends access my personal refrigerator but I'd not let them to access my bank account.
One can implement that as followed
class C1
{
private void MyMethod(double x, int i)
{
// some code
}
// the friend class would be able to call myMethod
public void MyMethod(FriendClass F, double x, int i)
{
this.MyMethod(x, i);
}
//my friend class wouldn't have access to this method
private void MyVeryPrivateMethod(string s)
{
// some code
}
}
class FriendClass
{
public void SomeMethod()
{
C1 c = new C1();
c.MyMethod(this, 5.5, 3);
}
}
That will of course generate a compiler warning, and will hurt the intellisense. But it will do the work.
On a side note, I think that a confident programmer should do the testing unit without accessing the private members. this is quite out of the scope, but try to read about TDD.
however, if you still want to do so (having c++ like friends) try something like
#if UNIT_TESTING
public
#else
private
#endif
double x;
so you write all your code without defining UNIT_TESTING and when you want to do the unit testing you add #define UNIT_TESTING to the first line of the file(and write all the code that do the unit testing under #if UNIT_TESTING). That should be handled carefully.
Since I think that unit testing is a bad example for the use of friends, I'd give an example why I think friends can be good. Suppose you have a breaking system (class). With use, the breaking system get worn out and need to get renovated. Now, you want that only a licensed mechanic would fix it. To make the example less trivial I'd say that the mechanic would use his personal (private) screwdriver to fix it. That's why mechanic class should be friend of breakingSystem class.
The friendship may also be simulated by using "agents" - some inner classes. Consider following example:
public class A // Class that contains private members
{
private class Accessor : B.BAgent // Implement accessor part of agent.
{
private A instance; // A instance for access to non-static members.
static Accessor()
{ // Init static accessors.
B.BAgent.ABuilder = Builder;
B.BAgent.PrivateStaticAccessor = StaticAccessor;
}
// Init non-static accessors.
internal override void PrivateMethodAccessor() { instance.SomePrivateMethod(); }
// Agent constructor for non-static members.
internal Accessor(A instance) { this.instance = instance; }
private static A Builder() { return new A(); }
private static void StaticAccessor() { A.PrivateStatic(); }
}
public A(B friend) { B.Friendship(new A.Accessor(this)); }
private A() { } // Private constructor that should be accessed only from B.
private void SomePrivateMethod() { } // Private method that should be accessible from B.
private static void PrivateStatic() { } // ... and static private method.
}
public class B
{
// Agent for accessing A.
internal abstract class BAgent
{
internal static Func<A> ABuilder; // Static members should be accessed only by delegates.
internal static Action PrivateStaticAccessor;
internal abstract void PrivateMethodAccessor(); // Non-static members may be accessed by delegates or by overrideable members.
}
internal static void Friendship(BAgent agent)
{
var a = BAgent.ABuilder(); // Access private constructor.
BAgent.PrivateStaticAccessor(); // Access private static method.
agent.PrivateMethodAccessor(); // Access private non-static member.
}
}
It could be alot simpler when used for access only to static members.
Benefits for such implementation is that all the types are declared in the inner scope of friendship classes and, unlike interfaces, it allows static members to be accessed.