-1

I have got a method with a single parameter of string class that I need to use to access another class in my project.

The following will be what I want it to do. Note that this syntax gives errors.

public string getId(string name) {
    string Id = name.GetId();
    return Id;
}

Assuming that the user enters "Joe" as the name, one would go to the class Joe.cs, which looks like this.

public class Joe {
    public string Id = 32;
    public string GetId() {
        return Id;
    }
}

What I want to happen here is for the first method to be able to get the GetId method from Joe if Joe is entered as a parameter. How would I do this? Thank you all.

  • 1
    Possible duplicate of [C# Reflection: How to get class reference from string?](https://stackoverflow.com/questions/1044455/c-sharp-reflection-how-to-get-class-reference-from-string) –  Jan 12 '19 at 06:58
  • 3
    `Joe` should rather be an **instance** of a single `User` class, not a class in himself. You can store a Dictionary from `"joe" -> User("joe", 32)` instead – OneCricketeer Jan 12 '19 at 06:59
  • 2
    Hard to say what you really need, but seems to be an [XY Problem](https://meta.stackexchange.com/a/233676) – OneCricketeer Jan 12 '19 at 07:02
  • You are kind of thinking about this wrong. But its hard to know how to help you as there is no details on the end result. – TheGeneral Jan 12 '19 at 07:02
  • I agree with above comment. If you describe your more general problem, we'll likely suggest you a better approach. –  Jan 12 '19 at 07:04

3 Answers3

1

This might point you in a better direction

The idea is to have a class called User that holds user information (funnily enough)

This way you can have a list of users (not a class for each one), as such you can easily look up a user and mess with them as much as you want

public class User
{
   public string UserName { get; set; }
   public string FavoriteColor { get; set; }
}

public class Program
{

   // A List to hold users
   private static List<User> _users = new List<User>();

   private static void Main(string[] args)
   {

      // lets add some people
      _users.Add(new User() { UserName = "Bob",FavoriteColor = "Red" });
      _users.Add(new User() { UserName = "Joe", FavoriteColor = "Green" });
      _users.Add(new User() { UserName = "Fred", FavoriteColor = "Blue" });

      // use a linq query to find someone
      var user = _users.FirstOrDefault(x => x.UserName == "Bob");

      // do they exist?
      if (user != null)
      {
         // omg yay, gimme teh color!
         Console.WriteLine(user.FavoriteColor);
      }


   }
}

Output

Red

You can take it a step further and ask the user to look up other users (what a time to be a alive!)

Console.WriteLine("Enter a user (case sensitive)");
var userName = Console.ReadLine();

var user = _users.FirstOrDefault(x => x.UserName == userName);

if (user != null)
{
   Console.WriteLine(user.FavoriteColor);
}
else
{
   Console.WriteLine("Game over, you failed");
}
Console.ReadLine();
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

You could build a Class that can contain the details you want to store, then build a Manager class that exposes public methods that can extract informations from the stored objects:

public class Friend : IComparable<Friend>
{
    public Friend() { }
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int FriendshipLevel { get; set; }

    int IComparable<Friend>.CompareTo(Friend other)
    {
        if (other.FriendshipLevel > this.FriendshipLevel) return -1;
        else return (other.FriendshipLevel == this.FriendshipLevel) ? 0 : 1;
    }
}

public class MyFriends : List<Friend>
{
    public MyFriends() { }
    public int? GetID(string FriendName)
    {
        return this.Where(f => f.FirstName == FriendName).FirstOrDefault()?.ID;
    }
    public Friend GetFriendByID(int FriendID)
    {
        return this.Where(f => f.ID == FriendID).FirstOrDefault();
    }
}

Build a sample class:

MyFriends myFriends = new MyFriends()
{
    new Friend() { ID = 32, FirstName = "Joe", LastName = "Doe", FriendshipLevel = 100},
    new Friend() { ID = 21, FirstName = "Jim", LastName = "Bull", FriendshipLevel = 10},
    new Friend() { ID = 10, FirstName = "Jack", LastName = "Smith", FriendshipLevel = 50},
};

Then you can extract informations on single/multiple objects using the public methods of the "Manager" class:

int? ID = myFriends.GetID("Joe");
if (ID.HasValue) // Friend Found
    Console.WriteLine(ID);

//Search a friend by ID
Friend aFriend = myFriends.GetFriendByID(32);
if (aFriend != null)
    Console.WriteLine($"{aFriend.FirstName} {aFriend.LastName}");

Or you can use LINQ to get/aggregate the required informations directly if there isn't a public method that fits:

// Get your best friends using LINQ directly
List<Friend> goodFriends = myFriends.Where(f => f.FriendshipLevel > 49).ToList();

goodFriends.ForEach((f) => Console.WriteLine($"{f.FirstName} {f.LastName}"));

//Best friend
Friend bestFriend = myFriends.Max();
Jimi
  • 29,621
  • 8
  • 43
  • 61
0

With respect to your Question : GetId method from Joe if Joe is entered as a parameter.

You can achieve that in the following ways also:

2. Method Using Named Method.

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

namespace Problem
{
    // Simple Model Class.
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Program
    {
        // Delegate.
        public delegate string PersonHandler(Person person);
        static void Main(string[] args)
        {
            List<Person> _persons = new List<Person>()
            {
                new Person(){Id=1,Name="Joe"},
                new Person(){Id=2,Name="James"},
                new Person(){Id=3,Name="Nick"},
                new Person(){Id=4,Name="Mike"},
                new Person(){Id=5,Name="John"},
            };

            PersonHandler _personHandler = new PersonHandler(GetIdOfPerson);

            IEnumerable<string> _personIds = _persons.Select(p => _personHandler.Invoke(p));

            foreach (var id in _personIds)
            {
                Console.WriteLine(string.Format("Id's : {0}", id));
            }
        }


        // This is the GetId Method.
        static string GetIdOfPerson(Person person)
        {
            string Id = person.Id.ToString();
            return Id;
        }
    }
}

2. Method Using Anonymous Moethod.

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

namespace Problem
{
    // Simple Model Class.
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Program
    {

        // Delegate.
        public delegate string PersonHandler(Person person);
        static void Main(string[] args)
        {
            List<Person> _persons = new List<Person>()
            {
                new Person(){Id=1,Name="Joe"},
                new Person(){Id=2,Name="James"},
                new Person(){Id=3,Name="Nick"},
                new Person(){Id=4,Name="Mike"},
                new Person(){Id=5,Name="John"},
            };

            PersonHandler _personHandler = delegate(Person person) 
            {
                string id = person.Id.ToString();
                return id;
            };

            // Retrieving all person Id's.
            IEnumerable<string> _personIds = _persons.Select(p => _personHandler.Invoke(p));

            foreach (var id in _personIds)
            {
                Console.WriteLine(string.Format("Id's : {0}", id));
            }
        }

    }
}

2. Method Using a Lambda Expression.

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

namespace Problem
{
    // Simple Model Class.
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    class Program
    {
        // Delegate.
        public delegate string PersonHandler(Person person);
        static void Main(string[] args)
        {
            List<Person> _persons = new List<Person>()
            {
                new Person(){Id=1,Name="Joe"},
                new Person(){Id=2,Name="James"},
                new Person(){Id=3,Name="Nick"},
                new Person(){Id=4,Name="Mike"},
                new Person(){Id=5,Name="John"},
            };

            PersonHandler _personHandler = (Person person) => person.Id.ToString();

            IEnumerable<string> _personIds = _persons.Select(p => _personHandler.Invoke(p));

            foreach (var id in _personIds)
            {
                Console.WriteLine(string.Format("Id's : {0}", id));
            }
        }
    }
}

Output:

enter image description here

Rehan Shah
  • 1,505
  • 12
  • 28