Alex
Alex

Reputation: 36101

C#: is there a way to make the creation of getters and setters automatic?

I'm writing a Mongo web application using their official C# driver.

In order to implement references, they have to be fetched manually.

so let's say we have

class User {
    ...
    public MongoDBRef Topic { get; set; }
}

To fetch the topic we need to do the following:

db.FetchDBRefAs<Topic>(user.Topic);

And to create a new one:

user.Topic = new MongoDBRef(TopicsTable, topic._id);

I decided to create a virtual property to make it more convenient:

    [BsonIgnore]
    public Topic _Topic
    {
        get
        {
            return db.FetchDBRefAs<Topic>(Topic);
        }
        set
        {
            CreatedAd = new MongoDBRef(TopicsTable, value._id);
        }
    }

Now I can use it like this:

 user._Topic = someTopic;
 anotherTopic = user._Topic;

Obviously it's a big pain to do this for all referenced objects.

Is there a way to make this process automatic?

Thanks

Upvotes: 3

Views: 377

Answers (2)

Oded
Oded

Reputation: 498904

You can use the Visual Studio code snippets.

Type in prop and two tabs, and you just need to fill in the type and name of the property.

There are built in snippets for a full property with backing field (propfull), read-only property (propg) and many more things - for example an empty constructor (ctor).

You can also create and use your own code snippets.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499840

You could use Visual Studio code snippets, I suspect. I've never done so myself, but I think this is precisely the sort of thing they're normally used for.

Upvotes: 5

Related Questions