C#10: A namespace-scoped Access modifier [duplicate] - c#

This question already has answers here:
C# access modifier for exposing class only within namespace
(3 answers)
Closed 12 months ago.
As in the title, I would love to see this in C#.
namespace PrivateStuff; //note: filescope namespace here!
public class PartiallyVisibleOutside
{
public int A;
namespace int B;
}
public class Test
{
public PartiallyVisibleOutside NC {get; private set;}
public void DoSmth()
{
NC.A = 100000 + NC.B; //OKAY til now!
Console.Write(NC.A);
}
}
//
namespace OUTSIDE;
public class OutsideClass
{
public PartiallyVisibleOutside Test;
void DoSmth()
{
Test.A = 100; //OKAY
Test.B = 100; //Compiletime-Error!
}
}
Does smth like this exist? Or shall i open up a feature-request at C#

There is no such feature and I think it is very niche thing to be implemented in near feature. Though you can simulate it by moving Test and PartiallyVisibleOutside into separate project (assembly) and marking B as internal.

Related

C#: Can't include class from annother namespace [duplicate]

This question already has answers here:
Call method in class from another class in C#
(5 answers)
Closed 1 year ago.
I have a strange problem.
I created two classes AdvertisementHelper(namespace AdvertisementHelper) and Doof (namespace blabla), now I want to use the method bad_code from class Doof in class AdvertisementHelper.
AdvertisementHelper.cs:
using blabla;
namespace AdvertisementHelper
{
class AdvertisementHelper
{
Doof d = new Doof();
d.bad_code();
}
}
Doof.cs:
namespace blabla
{
class Doof
{
public void bad_code()
{
}
}
}
This is not my first C# program, I have done this many times and I never had such problems.
blabla and AdvertisementHelper are part of the same Visual Studio project.
d.bad_code and bad_code is not defined in this context
.NET Framework 4.7.2
You cannot have code (a method call, that is) floating around just anywhere in a class.
class AdvertisementHelper
{
Doof d = new Doof(); // <= OK, because interpreted as class field
d.bad_code(); // <= doesn't work!
}
You need to put it into a method, for example.
class AdvertisementHelper
{
Doof d = new Doof(); // <= OK, because interpreted as class field
public void Execute()
{
d.bad_code(); // <= Inside a method = OK!
}
}

Why do i have access to internal methods outside of the namespace? [duplicate]

This question already has answers here:
internal vs public in C#
(8 answers)
Closed 2 years ago.
I am trying to understand access modifiers but i am a bit confused with how to use internal.
I have class in a namespace that looks like this:
namespace Grids
{
public abstract class Grid
{
internal abstract Vector2Int ToGrid(float worldX, float worldY);
internal Vector2Int ToGrid(Vector3 worldPoint) => ToGrid(worldPoint.x, worldPoint.z);
internal Vector2Int ToGrid(Vector2 worldPoint) => ToGrid(worldPoint.x, worldPoint.y);
}
}
This is then implemented in an inherited class like so:
namespace Grids
{
public class RectGrid : Grid
{
public int Width;
public int Height;
public Grid(int w, int h)
{
Width = w;
Height = h;
}
internal override Vector2Int ToGrid(float worldX, float worldY)
{
int col = Mathf.FloorToInt(worldX / Width);
int row = Mathf.FloorToInt(worldY / Height);
return new Vector2Int(col, row);
}
}
}
So i now make a class to use this Grid thats not part of the namespace:
using Grids;
using UnityEngine;
public class MapGenerator : MonoBehaviour
{
private RectGrid _rectGrid;
void Awake() {
_rectGrid = new RectGrid(1,1);
_rectGrid.ToGrid(Vector3.zero); // why do i have access to this function
}
}
Yet for some reason i have access to the functions which are suppose to be internal:
Why is this ? I don't want to expose this function i want it only accessible to my Map class which shares the same Grids namespace and will control what i do expose. Yet my MapGenerator class has access without even being part of the namespace?
Have i misunderstood how internal works here?
As per the documentation internal (C# Reference)
Internal types or members are accessible only within files in
the same assembly
As per your comment
[It's] difficult to design a way to hide these functions but still give
access to a specific class.
The standard access modifiers are fairly limited, you would need put the calling code in the same assembly to use internal. Additionally there is no way to grant an access list for calling classes unless you do this at runtime.
However, you could use an Explicit Interface Implementation. This will not completely limit access, but it will make it so you need to explicitly ask for it, and hides it any other time.
public interface IGrid
{
Vector2Int ToGrid(...);
}
public abstract class Grid : IGrid
{
Vector2Int IGrid.ToGrid(...) {}
}
Usage
var rectGrid = new RectGrid();
((IGrid)rectGrid).ToGrid(); // you need to explicitly cast to the interface

What are the best practices for class, method, variable cases/names for objects in C# class library? [closed]

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 7 years ago.
Improve this question
I'm a strong developer in some niche languages, and am organically learning C#, so trying to learn what are the best practices.
Can I get some feedback on what's best for the following sample code block where I'm building a Shopify integration for example.
namespace WMShopify
{
// Is it common to have the namespace and class the same?
public class WMShopify
{
// Are there different practices for private/public vars?
public string APIKey { get; set; } // Capital
public string password { get; set; } // lower case
public string secretString { get; set; } // Camel
private string _combinedVar; // Camel/underscore for private
}
// Should these be in a separate *.cs file?
public class WMShopifyOrders
{
// Method capital/lower/camel?
public int getOrderCount()
{
// lower/capital/camel?
int localMemberVar = 0;
return localMemberVar;
}
}
// Should these be in a separate *.cs file?
public class WMShopifyProducts
{
public List<string> getProductList()
{
return new List<string>();
}
}
}
Best practice: Come up with a standard that everyone agrees on and follows.
Verdicts: Written InLine
namespace WMShopify
{
// Is it common to have the namespace and class the same?
//No, namespace should probably be the name of the project itself.
public class WMShopify
//this looks like a configuration class
{
// Are there different practices for private/public vars?
public string APIKey { get; set; } // Capital
public string password { get; set; } // lower case
public string secretString { get; set; } // Camel
private string _combinedVar; // Camel/underscore for private
}
// Should these be in a separate *.cs file?
// I like to separate them because what happens when you have 100 classes, you just scroll forever?
public class WMShopifyOrders
{
// Method capital/lower/camel?
// I prefer capital
public int getOrderCount()
{
// lower/capital/camel? Sure
int localMemberVar = 0;
return localMemberVar;
}
}
// Should these be in a separate *.cs file? Yup
public class WMShopifyProducts
{
public List<string> getProductList()
{
return new List<string>();
}
}
}
While this question will likely end up getting closed, MSDN does provide pretty extensive guidelines that most .NET developers follow to some degree:
https://msdn.microsoft.com/en-us/library/ms229002(v=vs.100).aspx
Some highlights:
Don't use abbreviations; if you do use acronoyms, capitalize only the first letter, e.g. XmlReader, not XMLReader.
Use PascalCase for Methods and public Fields/Properties, use pascalCase for private fields, use _camelCase for private property backers.
Keep classes to one file - one exception would be defining an interface and its default implementation in the same file
Name methods using verbs (GetSomething(), SendSomething(), not Something()).
Don't name properties with Get or Set, e.g. Things is good but not GetThings
Name Booleans using "is" (IsEnabled, IsReadOnly, not Enabled).
Generic parameters should generally use T, or T(description), e.g. TSource, TKey, T1/T2/T3

Does c# have something like 'child' namespaces, or package scoping like in Java?

I don't understand why an explicit reference isn't required in this situation:
//SomeStaticClass.cs
namespace WhyDontINeedUsingStatement {
public static class SomeStaticClass {
public static string Thingy {
get { return "Behold! A thingy!"; }
}
}
public class SomeNonStaticClass {
public void DoSomethingUseful() {
var foo = 9;
}
}
}
// /SomeNamespace/SomeBoringClass.cs
namespace WhyDontINeedUsingStatement.SomeNamespace {
public class SomeBoringClass {
public static void DoSomething() {
var whatever = SomeStaticClass.Thingy;
var blah = new SomeNonStaticClass();
blah.DoSomethingUseful();
}
}
}
Why doesn't this require a using WhyDontINeedUsingStatement at the top? Aren't these separate namespaces, even though they start with the same thing?
I get that C# namespaces aren't quite the same thing as Java packages (and don't affect access control), but not why the second class is able to reference stuff from the first.
According to C# Language Specification Version 5.0, Section 9.2, it seems like using the . in a namespace declaration is syntactic sugar :
The qualified-identifier of a namespace-declaration may be a single
identifier or a sequence of identifiers separated by “.” tokens. The
latter form permits a program to define a nested namespace without
lexically nesting several namespace declarations. For example,
namespace N1.N2
{
class A {}
class B {}
}
is semantically equivalent to
namespace N1
{
namespace N2
{
class A {}
class B {}
}
}
So from inside of N2 you can see N1, hence why you can use it.

How to implement a partial class with static object definition in C#

//Found the solution...
The problem was in fact that I have an array of register filled on creation (contructor method) and that array wasn't instanciated.
To make it short, I've been too noob to even put a break point in the constructor to see if .Net handled a first chance exception.
Thanks again for all the repliers. You have been really helpful. :)
Sorry again for my noobness
What have I learned today :
-You never know how .net will merge your partial class
-Be more aware of first chance exceptions
//STATE CHANGE 2012/01/30 17:00 or so
Sorry, I narrowed on the wrong problem. The problem explained here doesn't seem to be caused by the code provided therefore this question no longer needs to exist.
Thanks to the repliers!
//DEPRECATED, CLOSED ... W/E
I have a device which can be contacted by various registry such 0x01, 0x02, 0x03...
Also, I work in a development environment and the application I produce are oriented for our own environment in a small compagny.
To turn these registry into object I have chosen, a long time ago, to make a class which have it's constructor private to create it's own and only instance (As I understand, multi-ton design pattern).
Since there's a lot of registry now and the class file is getting huge I want to split it into parts : The property/function definitions and the multi-ton objects.
When I try to use this ex:
Register.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
public int id { get; private set; }
public string foo { get; private set; }
public string bar { get; private set; }
protected Register(RegisterEnum id, string foo, string bar)
{
this.id = (int)id;
this.foo = foo;
this.bar = bar;
}
}
}
Register.enum.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
protected enum RegisterEnum
{
reg1 = 0x01,
reg2 = 0x02 //and so on
};
}
}
Register.const.cs :
namespace DeviceManagement.Register
{
public partial class Register
{
public static readonly Register reg1 =
new Register(RegisterEnum.reg1,"foo1","bar1");
public static readonly Register reg2 =
new Register(RegisterEnum.reg2,"foo2","bar2");
//there is plenty more
}
}
I intended to use it like
namespace DeviceManagement
{
class SomeClassA
{
public void doThisOnDevice(Device device)
{
device.doSomeStuffOn(Register.Register.reg1, SomeCommonlyUsedStrategy);
}
}
}
Here's a test I did :
namespace DeviceManagement
{
class SomeClassA
{
public void testIfNull()
{
if(Register.Register.reg1 == null)
MessageBox.Show("It is null");
}
}
}
The compilator, intellisense doesn't throw any error/warning but, when I run my project, the Register objects are never instanciated. Altough, I don't have that issue when all this code is in the same class (not partial) and obviously in the same file.
I'm kind of lost, please help me.
For starters you don't need to break it out into a partial class to have it over multiple files. If you want to lump it together then you can put it in a different sub namespace in separate files, anyway ...
It looks like a namespace issue, as you need to have Register.Register.reg1 to access the static const.
EDIT
Ok, so from the feedback and re-reading the question a few more times I get the feeling that the current design probably won't quite work all in the same class definition. I think you maybe trying to force something into some thing which won't go.
So, why not try something like this:
namespace DeviceManagement.Register
{
public class Register
{
public RegisterType Type { get; private set; }
public string Foo { get; private set; }
public string Bar { get; private set; }
public Register(RegisterType type, string foo, string bar)
{
Type = type;
Foo = foo;
Bar = bar;
}
}
public enum RegisterType
{
reg1 = 0x01,
reg2 = 0x02 //and so on
}
public static class RegisterFactory
{
private static readonly Dictionary<RegisterType, Register> _dictionary = new Dictionary<RegisterType, Register>
{
{ RegisterType.reg1, new Register(RegisterType.reg1, "foo", "bar") },
{ RegisterType.reg2, new Register(RegisterType.reg2, "foo2", "bar2") }
};
public static Register GetRegister(RegisterType type)
{
return _dictionary[type];
}
}
}
And consume the register:
public class SomeClassA
{
public void DoThisOnDevice(Device device)
{
device.DoSomeStuffOn(RegisterFactory.GetRegister(RegisterType.reg1), SomeCommonlyUsedStrategy);
}
}
You could then take it a step further and load in the registry details from a configuration file which parses it on start up of your application to, you could then choose the registry type to work on from your UI etc.
Hope I've not got the wrong end of the stick.
I copy pasted your code and it works fine for me.
My advice is to use the Class View of Visual Studio. Here you can easily see if all the partial classes are defined within the same namespace and with the exactly same class name. If not, too many namespaces or classes will appear.

Categories

Resources