views:

48

answers:

2

I am sortof using a repository pattern to extract information from a database. I have two classes, report and reportRepository.

The trouble I have is that since reportReposity has to fill in all the details for the report object, all the members in the report have to be publicly accessible.

Is there a way so that I can ensure that only the repository class can access some of the methods of the report class and only it can set some of the properties that other classes cannot, sort of like what friend does in c++. Or is there a completely different way of handling this situation?

I am using C# in ASP.NET 2.0

+1  A: 

You can apply access modifiers to properties, e.g:

public string Name { get; internal set; }

Internal gives write access to the specified property for any types in the same assembly.

Matthew Abbott
I am working with a C# website and unfortunately I think it puts every class in the same assembly so all the classes will have access to the internal methods.
TP
Why not push them out to their own class library and reference it to the website?
Matthew Abbott
@TP - check out my recent question: http://stackoverflow.com/questions/3878391/how-can-i-hide-setters-from-all-but-one-assembly I had to do the same thing as you. Use the 'InternalsVisibleTo' directive.
RPM1984
@RPM1984 InternalsVisibleTo would solve my problem by it's available only on the .net 4 platform. I am restricted to .net 2.0 for this project.
TP
+1  A: 

This looks a bit funky but it does what your after, any property with a 'protected' modifier will only be accessable within that class AND any derived classes

public class Person
{
    public string Name { get; protected set; }
    public int Age { get; protected set; }
}

public class PersonRepository
{
    public Person Get()
    {
        return new PersonBuilder("TestName", 25);
    }

    private class PersonBuilder : Person
    {
        public PersonBuilder(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }
    }
}

So unless your within the repository you can't see the Person derived class PersonBuilder which has a constructor that populates the protected properties of Person. Externally it looks like your magically populating fields without using setters or constructors.

Sam Kirkpatrick
Quite interesting actually. I wish C# had the friend keyword but I guess that's a debate on its own.
TP