Call an Object Member Dynamically - CSharp Custom Type

CSharp examples for Custom Type:dynamic type

Description

Call an Object Member Dynamically

Demo Code


using System;//  ww w  .ja  v a  2 s.co m
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

    class myType
    {
        public myType(string strval)
        {
            str = strval;
        }

        public string str {get; set;}

        public int countVowels()
        {
            char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
            int vowelcount = 0;
            foreach (char c in str)
            {
                if (vowels.Contains(c))
                {
                    vowelcount++;
                }
            }
            return vowelcount;
        }
    }

class MainClass
    {
        static void Main(string[] args)
        {
            dynamic dynInstance = new myType("The quick brown fox jumped over the...");

            int vowels = dynInstance.countVowels();
            Console.WriteLine("There are {0} vowels", vowels);

            dynInstance.thisMethodDoesNotExist();
        }
    }

Result


Related Tutorials