tags:

views:

44

answers:

3

UPDATE: Sorry, I was wrong, StringBar is returned. Let's see if I can work out how to delete this question.

Imagine the following class:

public class Foo
{
    public int Bar { get; set; }

    public string StringBar
    {
        get { return Bar.ToString(); }
    }

    public void DoSomething()
    {
    }
}

If I write: typeof(Foo).GetProperties(), the StringBar property info is not returned, I presume because C# thinks of it as a method, not a property.

From a programmers perspective though, there is a difference: a method would usually be expected to cause some state change, whereas a property wouldn't.

What is the best way to get the Bar and StringBar properties, but not the DoSomething method (without specifically referring to their names obviously)?

+2  A: 

I dispute your claim that StringBar won't be returned. It's a perfectly ordinary property.

I don't suppose in your real code it's non-public, is it?

Counter-example code - with Foo exactly as you presented it:

using System;

class Test
{
    static void Main()
    {
        foreach (var prop in typeof(Foo).GetProperties())
        {
            Console.WriteLine(prop.Name);
        }
    }
}

Results:

Bar
StringBar
Jon Skeet
A: 

This prints StringBar and Bar for me.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            foreach (var item in typeof(Foo).GetProperties())
                Console.WriteLine(item.Name);

            Console.ReadKey();
        }

        public class Foo
        {
            public int Bar { get; set; }

            public string StringBar
            {
                get { return Bar.ToString(); }
            }

            public void DoSomething()
            {
            }
        }

    }
}
Pondidum
A: 

Of course StringBar property will be returned! I'm absolutely sure! It's still a property, with get action only(read-only).

Danny Chen