473,246 Members | 1,614 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

Restricting access of class variable to another single class?

Hi all,

The next few paragraphs put my question in context, but feel free to
skip down to the end if you don't care *why* I need the answer! :)

****************************************
*** Start of long-winded description ***
****************************************

I've got some classes that define a tree structure. When the Parent
property of an item is changed, it automatically updates the Children list.

The opposite is also true - if you add an item to a Children list, it's
parent is automatically updated.

The way this second part works, is with an event (fired when items are
added to the list) like this:

children.Added += delegate(object sender,
ChildList<T>.ChildListEventArgs<T> e) { e.Item.parent = (T)this; };

Notice the lowercase p in parent. If I change this to a P, then I'll get
a StackOverflow, because setting the parent, adds to the child list, and
adding to the child list sets the parent. This works fine, because
everything is in one class (the tree is a tree of one type).

Now, I've extended it slightly to support ClassA having children of
ClassB, and ClassB has a parent of ClassA.

My problem, is that from within ClassB, when the child list is modified,
I need to set the parent of ClassA. My current method requires that the
parentClassB property within ClassA be internal (if I use the public
property, I'll overflow the stack again). However, it's important people
(me) don't "accidentally" use this variable when meaning to use the
public property (else my magic code won't get called, undermining the
whole point of me abstracting the tree stuff!).

****************************************
*** End of long-winded description ***
****************************************

So... In short - is there any way to restrict access, like "internal",
but only to subset of classes within the DLL?

If not, the only way to make sure my code is used properly, is to move
ClassA and ClassB into a separate DLL, so only they can set each others
internal data.

The problem with that, is that ClassA and ClassB then need to be public,
and that means anyone can reference my DLL and use my classes, whereas
if everything is in one, they can be internal classes.
Are there any solutions? :-(
Nov 30 '05 #1
6 1746
> So... In short - is there any way to restrict access, like "internal",
but only to subset of classes within the DLL?


What you're after is something like the "friend" designation available
in some other languages. C# doesn't have it, so no.

That said, one way to at least reduce confusion is to expose the
internal "set parent without fiddling with parent's child list"
operation as a method, rather than a property (or, even worse, exposing
the field directly). For example, you could have:

public ClassB Parent
{
get { return this._parent; }
set
{
SetParent(value);
... update parent's children ...
}
}

internal void SetParent(ClassB newParent)
{
this._parent = newParent;
}

Then at least the code within your DLL would know that if it's setting
Parent it's getting the public version, while to do an internal set
(with no side effects) it has to call the method, and the difference
will be more visible (rather than being nothing more than a case
difference: parent versus Parent).

Nov 30 '05 #2
Bruce Wood wrote:
That said, one way to at least reduce confusion is to expose the
internal "set parent without fiddling with parent's child list"
operation as a method, rather than a property (or, even worse, exposing
the field directly). For example, you could have:

public ClassB Parent
{
get { return this._parent; }
set
{
SetParent(value);
... update parent's children ...
}
}

internal void SetParent(ClassB newParent)
{
this._parent = newParent;
}

Then at least the code within your DLL would know that if it's setting
Parent it's getting the public version, while to do an internal set
(with no side effects) it has to call the method, and the difference
will be more visible (rather than being nothing more than a case
difference: parent versus Parent).


I thought about that too (it stops intellisense picking the wrong one
parent/Parent), though it's not as nice as I'd hoped. I'll go with it
for now (since it's the best solution), but I think my whole tree thing
is a bit messy now, so might re-plan it a bit better at some point!
Nov 30 '05 #3
You can gain knowledge about who is calling your method by using the StackTrace
class as shown below.
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
Type callingType=methodBase.DeclaringType;

stackTrace.GetFrame(1) gets the immediate caller of your method. You can
then get the type declaring the method that made the invocation by inspecting
the DeclaringType property of the MethodBase class. You can use this information
to restrict calls to a method by type.

A word of caution is due; inspecting the stack trace can be slow.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 30 '05 #4
Incidentally, that's why I started using the _xxx notation for private
member fields. I hate stupid prefixes, but boy, does it make it easier
to use Intellisense. No more picking the field instead of the property,
or vice versa.

It also has the advantage that you see the fields first in the
debugger's Local window, so you avoid the endless slow scrolling as the
debugger evaluates all of the properties from A to O just to get to the
"parent" field.

Dec 1 '05 #5
Bruce Wood wrote:
Incidentally, that's why I started using the _xxx notation for private
member fields. I hate stupid prefixes, but boy, does it make it easier
to use Intellisense. No more picking the field instead of the property,
or vice versa.

It also has the advantage that you see the fields first in the
debugger's Local window, so you avoid the endless slow scrolling as the
debugger evaluates all of the properties from A to O just to get to the
"parent" field.


heh, I've used _xxx a few times, but it's so ugly, I always go back to
lower-case for fields and ProperCase(!) for properties. An addition to
your reasons, my reason was so that in a method with its own local
variables, it's easy to distinguish what's "object-scoped", and won't
disappear when this method ends! :)
Dec 1 '05 #6
Anders Norås wrote:
You can gain knowledge about who is calling your method by using the
StackTrace class as shown below.

<snip>

I thought about that (after the response in the EventHandling thread),
but it's a little nasty. I think I'll use a method to set it for now, so
it's not going to slow things down, or leave an ugly field visible
externally!
Dec 1 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: Gaurav Veda | last post by:
Hi ! I am a poor mortal who has become terrified of Python. It seems to have thrown all the OO concepts out of the window. Penniless, I ask a basic question : What is the difference between a...
6
by: Peter Frost | last post by:
Please help I don't know if this is possible but what I would really like to do is to use On Error Goto to capture the code that is being executed when an error occurs. Any help would be much...
49
by: Yannick Turgeon | last post by:
Hello, We are in the process of examining our current main application. We have to do some major changes and, in the process, are questionning/validating the use of MS Access as front-end. The...
7
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I...
4
by: Dennis C. Drumm | last post by:
Is there a way with C# to allow one class access to a method or field of another class, without making that method or field visible to all other classes, as would be the case when making the method...
4
by: Danny Tuppeny | last post by:
Hi all, The next few paragraphs put my question in context, but feel free to skip down to the end if you don't care *why* I need the answer! :) **************************************** ***...
1
by: ward | last post by:
Good morning everyone. I'm building a very simple content management site that tracks "tasks." The options available are: 1. Add Task 2. Edit Task 3. View Task 4. Print Task
9
by: LamSoft | last post by:
Class B { public B() {} } Class A : B { public static string ABC = "myABC"; public A() {} }
2
by: sant.tarun | last post by:
Hi, I am facing some some problem in restricting the access of a variable.... My question is described below..... Let I have two different C source files 'a.c' and 'b.c'. In the file 'a.c'...
4
by: Christopher | last post by:
I am surprised this hasn't come up for me more in the past, but the situation is: I need to have an interface that is usable for all I need to have an interface that is only usable for some I...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.