So I've been using this code to automatically serialize my "User" business object which has been working great.
[WebMethod]
public MyUser GetUserFromCard(string code, string cardNumber)
{
var repo = new MyRepositry(cinemaCode);
string parameters = string.Empty;
parameters = MyRepositry.MakeParameter("CardNumber", cardNumber);
return repo.FindMember(parameters);
}
which is returning this xml
<MyUser>
<BirthDate>1982-04-13T00:00:00</BirthDate>
<Address>market st</Address>
<Suburb>sydney</Suburb>
<State>NSW</State>
<Postcode>2000</Postcode>
<UserName>test user</UserName>
<Password>passw0rd</Password>
<FirstName>test</FirstName>
<LastName>user</LastName>
<Email>test#land.com.au</Email>
<ReceiveEmail>true</ReceiveEmail>
<CardNumber>454543523443</CardNumber>
<Points>10</Points>
<Rewards>
<Reward/>
<Reward/>
</Rewards>
</MyUser>
My Problem is that the rewards array is returning the correct number of elements but they are empty. Both the MyUser and Reward classes have absolutly no annotations or other methods to perform custom serialization.
Any Ideas?
Can you show the Reward class? In particular, for use with XmlSerializer it must have a public parameterless constructor, and all* the properties must be public with both getters and setters; so the following would behave like you've described:
public class Reward {
private readonly string name;
public Reward(string name) {
this.name = name;
}
public string Name {get {return name;}}
}
but this would work:
public class Reward {
public string Name {get;set;}
}
*=with some minor caveats.
Related
I have two classes, one ExampleClass and one ExampleClassManager, which contains a list of ExampleClass.
ExampleClass has a private _id field, which I want to set in the ExampleClassManager class. Is this possible?
public class ExampleClass
{
//Fields
private string _id; //Should be set in ExampleClassManager
}
public class ExampleClassManager
{
//Fields
List<ExampleClass> exampleClassList = new List<ExampleClass>();
}
There're several possible options.
Make it public (not recommended, because it's bad)
Create a public property for access
Create a public method to set the value (basically the same as second option)
Do it with reflection
I would prefer the second option, because I think it's the cleanes way. When you have no chance to change the modifier you will have to use the fourth option.
For this you can use properties.
msdn doc
answer on stackoverflow
Example 1: (like Kevin Cook says) ExampleClass takes the id in the constructor and then id can't be changed:
public class ExampleClass
{
public class ExampleClass(string id)
{
_id = id;
}
//Fields
private readonly string _id; //note the use of **readonly**
public string Id { get {return _id; } } //So ExampleClassManager can see the id
}
usage:
var actualObject = new ExampleClass("abc123");
string myObjectId = actualObject.Id // This should be what was passed in... "abc123"
I could give a code example to show how to change the id via a property but I've yet to see a case where you'd want an object identifier to change once it has been created. There would easily be other fields that you may want to change but that is a different question.
I have just written a small piece of code and it struck me that I am not sure what method of initialisation is best practice when it comes to initialising my member variables which will be exposed and used via properties. Which is the best way to initialise my member variables out of the two examples below and more importantly why?
Example 1:
private string m_connectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
private string m_providerName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
public string ProviderName
{
get { return m_providerName; }
set { m_providerName = value; }
}
public EntityClusterRefreshServiceDatabaseWorker()
{
}
Example 2:
private string m_connectionString;
private string m_providerName;
public string ConnectionString
{
get { return m_connectionString; }
set { m_connectionString = value; }
}
public string ProviderName
{
get { return m_providerName; }
set { m_providerName = value; }
}
public EntityClusterRefreshServiceDatabaseWorker()
{
ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
ProviderName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
}
NOTE: Assume that I am not using these variables in a static context.
It really doesn't matter which of those you use, except in the very odd situation where a base class constructor calls an overridden member, in which case the timing would change: instance variable initializers are run before the base class constructor call, whereas obviously the constructor body is executed afterwards.
In the latter case, you can make your code a lot simpler though using automatically implemented properties:
public string ConnectionString { get; set; }
public string ProviderName { get; set; }
public EntityClusterRefreshServiceDatabaseWorker()
{
// Code as before
ConnectionString = ...;
ProviderName = ...;
}
You can't do this with the first form, as automatically implemented properties don't have any way of specifying an initial value.
(You may also want to consider making the setters private, but that's a separate concern.)
You are essentially doing the same thing but writing it in a different form.
I always prefer (and use) the second aprroach because I don't like methods being executed in the middle of nowhere. It's better to split things. Attributes are declared on class body and initialized on class constructor.
As long as the connection strings are not supposed to be changed, you can initialize them as static readonly:
private readonly static string m_connectionString = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ConnectionString;
private readonly static string m_providerName = ConfigurationManager.ConnectionStrings["ApplicationDefault"].ProviderName;
readonly variables are allowed to be initialized only in class declaration/contructor and are better optimized for performance than regular private variables.
And back on the question - it really doesn't matter where you'll initialize these.
Drop the fields and go for automatic properties & make your setters private.
public string ConnectionString {get; private set;}
public string ProviderName {get; private set;}
Rob
I have a class in test.cs in which I have a string value string user="testuser". I want to use the test.cs's user value in another class. How can I do this?
Declare the string public:
public string user = "testuser";
Then you can access it from another class via
Test.user
However, depending on what exactly you want, you should perhaps make the field read-only:
public readonly string user = "testuser";
Or use a property, bound to a backing field:
public string User
{
get { return this.user; }
}
In fact, properties are the canonical way of making information accessible from the outside except for very few, very special cases. Public fields are generally not recommended.
As Ant mentioned in a comment, there is also the option of making it a constant (assuming it is, in fact, a constant value):
public const string user = "testuser";
Make a public property.
Public string TestUser
{
get { return testUser;}
}
You should make a property of user and expose this to any other class that want to read or write it's value.
class MyClass
{
private static string user;
public static string User
{
get { return user; }
set { user = value; }
}
}
class MyOtherClass
{
public string GetUserFromMyClass()
{
return MyClass.User;
}
}
public class AClass
{
// declarations
private string _user = "testUser";
// properties
public string User { get { return this._user;} set { this._user = value; } }
}
then call your class property, e.g.
AClass myClass = new AClass();
string sYak = myClass.User;
As suggested in the earlier answers, making "user" into a Property is the ideal technique of accomplishing this. However, if you want to expose it directly anyhow, you should use static to avoid having to instantiate an object of that class. In addition, if you don't want the demo class to manipulate the value of user, you should declare is readonly as well, like below
public static readonly user="text user";
I have a lot of constant string values in my application which I want to have as strongly typed objects in C# for code reuse and readability. I would like to be able to reference the string value like so:
Category.MyCategory //returns a string value ie “My Category”
Category.MyCategory.Type.Private //returns a string value ie “private”
Category.MyCategory.Type.Shared //returns a string value ie “shared”
I have started by implementing the following classes each containing a list of public string valued fields with a public property which exposes the child.
Category, MyCategory, Type
However I already know this is not the way to go so could do with a bit of advice on this one.
An example of this is where I am using the Syndication classes to add a category to an atom feed. I am creating the items in this feed dynamically so need to use the notation as shown.
item.Categories.Add( new SyndicationCategory
{
Scheme = Category.PersonType,
Label="My Category",
Name=Category.MyCategory.Type.Private
});
Keep your string constants close to where you need them, IMO having a class that just declares constants is an OO antipattern
Why not simply implement them as classes with overridden ToString implementations?
public class MyCategory
{
private readonly MyType type;
public MyCategory()
{
this.type = new MyType();
}
public MyType Type
{
get { return this.type; }
}
// etc.
public override string ToString()
{
return "My Category";
}
}
public class MyType
{
public override string ToString()
{
return "My Type";
}
// more properties here...
}
However, for general purposes, consider whether the strings in themselves don't represent concepts that are better modeled as full-blown objects.
I completely agree with Rob. If you still want to have a "bag of strings", you could try using nested classes, something like below. I don't really like it, but it works.
public class Category
{
public class MyCategory
{
public const string Name = "My Category";
public class Type
{
public const string Private = "private";
public const string Shared = "shared";
}
}
}
I'm trying to build a class which will initalise its self either by passing in a reference to a record in a database (with the intention that a query will be run against the database and the returned values for the objects properties will be set therein), or by specifying the values "by hand" - this no database call is required.
I've looked at a couple textbooks to discover the "Best-practice" for this functionality and sadly I've come up short.
I've written a couple sample console apps reflecting what I believe to be the two most probable solutions, but I've no Idea which is the best to implement properly?
Sample App #1 uses what most books tell me is the "preferred" way but most examples given alongside those claims do not really fit the context of my situation. I'm worried in here that the flow is not as readable as App #2.
using System;
namespace TestApp
{
public class Program
{
public static void Main(string[] args)
{
var one = new OverloadedClassTester();
var two = new OverloadedClassTester(42);
var three = new OverloadedClassTester(69, "Mike", 24);
Console.WriteLine("{0}{1}{2}", one, two, three);
Console.ReadKey();
}
}
public class OverloadedClassTester
{
public int ID { get; set; }
public string Name { get; set; }
public int age { get; set; }
public OverloadedClassTester() : this(0) { }
public OverloadedClassTester (int _ID) : this (_ID, "", 0)
{
this.age = 14; // Pretend that this was sourced from a database
this.Name = "Steve"; // Pretend that this was sourced from a database
}
public OverloadedClassTester(int _ID, string _Name, int _age)
{
this.ID = _ID;
this.Name = _Name;
this.age = _age;
}
public override string ToString()
{
return String.Format("ID: {0}\nName: {1}\nAge: {2}\n\n", this.ID, this.Name, this.age);
}
}
}
This Sample (App #2) "appears" more readable - in that I think it's easier to see the flow of operation. However it does appear efficient in terms of characters saved :p. Also, is it not dangerous that it calls a method of the object before it's fully initialised, or is this not a concern?
using System;
namespace TestApp
{
public class Program
{
public static void Main(string[] args)
{
var one = new OverloadedClassTester();
var two = new OverloadedClassTester(42);
var three = new OverloadedClassTester(69, "Mike", 24);
Console.WriteLine("{0}{1}{2}", one, two, three);
Console.ReadKey();
}
}
public class OverloadedClassTester
{
public int ID { get; set; }
public string Name { get; set; }
public int age { get; set; }
public OverloadedClassTester()
{
initialise(0, "", 21); // use defaults.
}
public OverloadedClassTester (int _ID)
{
var age = 14; // Pretend that this was sourced from a database (from _ID)
var Name = "Steve"; // Pretend that this was sourced from a database (from _ID)
initialise(_ID, Name, age);
}
public OverloadedClassTester(int _ID, string _Name, int _age)
{
initialise(_ID, _Name, _age);
}
public void initialise(int _ID, string _Name, int _age)
{
this.ID = _ID;
this.Name = _Name;
this.age = _age;
}
public override string ToString()
{
return String.Format("ID: {0}\nName: {1}\nAge: {2}\n\n", this.ID, this.Name, this.age);
}
}
}
What is the "correct" way to solve this problem, and why?
Thanks,
I would definitely chain the constructors, so that only one of them does the "real work". That means you only have to do the real work in one place, so if that work changes (e.g. you need to call some validation method at the end of the constructor) you only have one place where you need to change the code.
Making "simple" overloads call overloads with more parameters is a pretty common pattern IME. I find it more readable than the second version, because you can easily tell that calling one overload is going to be the same as calling the "bigger" one using the default values. With the second version, you have to compare the bodies of the constructors.
I try not to have more than one constructor which chains directly to the base class wherever possible - unless it's chaining to a different base class constructor, of course (as is typical with exceptions).
Do not use database calls in a constructor. This means your constructor is doing a lot of work. See http://misko.hevery.com/code-reviewers-guide/ (Google guide for writing testable code).
Apart from this, chaining constructors (option 2) looks good. Mostly because as you say it is readable. But why are you assigning this.Name etc in the constructor and doing it again in initialize. You could assign all values in initialize.
Maybe something like this?
public class OverloadedClassTester
{
public int Id { get; private set; }
public string Name { get; private set; }
public int Age { get; private set; }
public OverloadedClassTester (Person person)
: this (person.Id, person.Name, person.Age) { }
public OverloadedClassTester(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
}
public override string ToString()
{
return String.Format("Id: {0}\nName: {1}\nAge: {2}\n\n",
Id, Name, Age);
}
}
maybe it would be better to use optional parameters? In this case, you would create a single constructor and initialize the values to the parameters you wish to set.
More information: link text
I prefer #1, the chaining constructors, from a maintenance perspective. When someone comes back to edit the code later on, you wouldn't want them to edit the initialise() method and not realize that it is being called from a constructor. I think it is more intuitive to have all the functional parts in a constructor of some kind.
Personally, I use constructor chaining like that all the time.