12 Replies - 104221 Views - Last Post: 28 August 2012 - 08:49 AM Rate Topic: -----

#1 rnty   User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 283
  • Joined: 14-August 12

Employee Details using C sharp

Posted 24 August 2012 - 10:46 AM

Hello everyone
I am new to c#.I am trying to write a program to handle employee details using Indexers.Kindly help me out with the logic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

            while (true)
            {
                Console.Clear();
                Console.WriteLine("Menu");
                Console.WriteLine("====");
                Console.WriteLine("1.Add an Employee Record");
                Console.WriteLine("2.Display Employee Record(s)");
                Console.WriteLine("3.Exit");

                Console.WriteLine("Enter your choice");
                int ch = Int32.Parse(Console.ReadLine());
                switch (ch)
                {
                    case 1:
                        Employee_List emplist = new Employee_List();
                        emplist.AddEmployee();
                        break;
                    case 2:
                        for (int i = 0; i < 10; i++)
                        {
                            Console.WriteLine();
                        }
                        break;

                }
            }
        }
    }

    class Employee
    {
        string ename,edept;
        int eno,esal;

        public Employee()
        {
            ename="";
            edept="";
            eno=0;
            esal=0;
        }

        public Employee(string name,string dept,int num,int sal)
        {
            ename=name;
            edept=dept;
            eno=num;
            esal=sal;
        }

        public Employee this[int pos]
        {
            get
            {
                if(pos>0 && pos<=9)
                {
                    return Employee;
                }
                
            }
        }
        
    }

        class Employee_List
        { 
            Employee[] emp=new Employee[10];
            int index=0;

            public void AddEmployee()
            {
                string name,dept;
                int num,sal;

                Console.WriteLine("Enter the details");
                Console.WriteLine("NAME:");
                name=Console.ReadLine();
                Console.WriteLine("DEPARTMENT:");
                dept=Console.ReadLine();
                Console.WriteLine("EMPLOYEE NUMBER:");
                num=Int32.Parse(Console.ReadLine());
                Console.WriteLine("SALARY:");
                sal=Int32.Parse(Console.ReadLine());

                emp[index]=new Employee(name,dept,num,sal);
                index++;
     
            }
        }

    }


Will be really grateful.Thank You

Is This A Good Question/Topic? 0
  • +

Replies To: Employee Details using C sharp

#2 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15361
  • View blog
  • Posts: 61,605
  • Joined: 12-June 08

Re: Employee Details using C sharp

Posted 24 August 2012 - 11:01 AM

Help with *what* logic?
Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Employee Details using C sharp

Posted 24 August 2012 - 11:05 AM

As this is obviously homework let me be clear: We won't do your homework for you. We don't know the assignment guidelines or goals or instructions or grading points etc.

If you have a SPECIFIC question about an error etc. we can help with that.

But if you don't understand the assignment your best bet is to go to your teacher.
Was This Post Helpful? 0
  • +
  • -

#4 rnty   User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 283
  • Joined: 14-August 12

Re: Employee Details using C sharp

Posted 24 August 2012 - 11:16 AM

First of all this is not homework.I am learning C# on my own.I have programmed before in C,C++,Java.Indexers is a new concept for me so I need some help with the logic.I don't know how this idea came to my mind(maybe because it is a common problem that I have implemented in C,C++).
Coming to the logic-->I am trying to add and display employee records.
I take a class Employee and use an indexer inside it.Using another class called Employee_Listing I try to input data into Employee.
Was This Post Helpful? 0
  • +
  • -

#5 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7139
  • View blog
  • Posts: 24,247
  • Joined: 05-May 12

Re: Employee Details using C sharp

Posted 24 August 2012 - 12:00 PM

Unfortunately, your code doesn't even compile.

I think you missed out on part of the concept of indexers. If you were thinking/hoping that lines 63-73 would somehow be able to reach outside its scope and discover it's location within the employee array on line 79, it won't.

The C# indexer is parallel to the C++ operator[]. It just happens to expose things as a property rather than as a method.

Here is one way to abuse the indexer:
    class Employee
    {
        string ename,edept;
        int eno,esal;

        public Employee()
        {
            ename="";
            edept="";
            eno=0;
            esal=0;
        }

        public Employee(string name,string dept,int num,int sal)
        {
            ename=name;
            edept=dept;
            eno=num;
            esal=sal;
        }

        public object this[string field]
        {
            get
            {
                switch(field)
                {
                case "EmployeeNo":    return eno;
                case "Name":          return ename;
                case "Department":    return edept;
                case "Salary":        return esal;
                }
                return null;
            }
        }
        
    }

:
:
Employee emp = new Employee("Vader", "Conquest", 1, 0);
Console.WriteLine(emp["Name"]);


This post has been edited by Skydiver: 24 August 2012 - 12:30 PM

Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Employee Details using C sharp

Posted 24 August 2012 - 03:42 PM

You'll find a lot of the old fashioned concepts of C++ just don't hold up in C#. For example, nobody would do this:
079 Employee[] emp=new Employee[10];

Unless I'm forced to use an array such as a byte[] for TCP communication, or to work with images on a pixel level... Nobody I know uses primitive arrays. In C# we have advanced and easier to use types like List<T>

So in your example we would just make:
List<Employee> AllEmployees = new List<Employee>;

There is no predefined size on a list like there is on an array. You can just keep adding to it.

Employee bob = new Employee("Bob", "Smith", 47, "Accounting");
AllEmployees.Add(bob);


List<T> is enumerable so you can make use of Foreach()

foreach(Employee temp in AllEmployees)
{
   decimal dollars = temp.RunPayroll();
}


And this is just one example of one thing. Mostly it looks like you are trying to find syntactical equivalents in C# for your C++ experience, when you should be trying to learn how things are actually done in C# in today's world.


First learn the language by working 2-5 "Learn C# in 30 days" type books cover to cover. Do a couple hundred on-line tutorial projects where you build what you're told to build, the way you are told to build it WITH AN EXPLANATION OF WHY so you can learn.

Then later you can start architecting your own simple stuff. Build a calculator. Build a DVD library program. Etc. Stuff that doesn't involve the complexity of a game. Then move up to games.



There are three routes people seem to take when learning programming.
  • Just start trying to create programs
  • Start taking apart other programs and try to figure out the language by reverse engineering
  • Follow a guided learning course (school or self-teaching books)


For the life of me I can't figure out why people try 1 & 2. I strongly suggest taking the guided learning approach. Those book authors go in a certain order for a reason: They know what they're doing and they know the best order to learn the materials.

Quote

Where do I start?


You start by learning a coding language FIRST.
Learn to plan before you type.
THEN you start designing software with a purpose.


If this sounds like you

Newbie/Rookie said:

I have a little programming experience but I need to write ...
read this section
Spoiler


Otherwise, you can just jump to the resources here:
Some of the tutorials below are for C# or Java not C, C++, VB.NET [...]. But the conceptual stuff of classes, object oriented design, events etc. are not language specific and should give you enough guidance in theory of program development for you to be able to look-up specific code example in your chosen coding language.



Resources, references and suggestions for new programmers. - Updated Mar 2012
Spoiler

Was This Post Helpful? 1
  • +
  • -

#7 rnty   User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 283
  • Joined: 14-August 12

Re: Employee Details using C sharp

Posted 25 August 2012 - 01:35 AM

Quote

Do a couple hundred on-line tutorial projects where you build what you're told to build, the way you are told to build it WITH AN EXPLANATION OF WHY so you can learn.

How do I do this?

@SkyDiver:I want to store and display more than one employee records.Storing the records is easy but the problem is displaying the records.
using System;

namespace EmployeeIndexer
{
    class Employee
    {
        string[] edept=new string[10];
        string[] ename=new string[10];
        int[] eno=new int[10];
        int[] esal=new int[10];
        int index = 0;

        public Employee()
        {
            edept[index] = "";
            ename[index] = "";
            eno[index] = 0;
            esal[index] = 0;
        }

        public void AddRec(string d, string n, int no, int s)
        {
            edept[index] = d;
            ename[index] = n;
            eno[index] = no;
            esal[index] = s;
        }

        public void this[int pos]
        {
            get
            {
                Console.WriteLine("{0} {1} {2} {3}",edept[pos],ename[pos],eno[pos],esal[pos]);              
            }
        }
    }

    class Employee_List
    {
        Employee[] e;
        int size=0;

        public Employee_List()
        {
            e = new Employee[10];
        }
        public void AddFunc()
        {
            string n, d;
            int s, no;

            Console.WriteLine("Enter the number of records you want to add:");
            size = Int32.Parse(Console.ReadLine());

            for (int i = 0; i < size; i++)
            {
                Console.WriteLine("Record Number {0}",i);
                Console.WriteLine("Name:");
                n = Console.ReadLine();
                Console.WriteLine("Number:");
                no = Int32.Parse(Console.ReadLine());
                Console.WriteLine("Dept:");
                d = Console.ReadLine();
                Console.WriteLine("Salary:");
                s = Int32.Parse(Console.ReadLine());

                e[i].AddRec(d,n,no,s);
            }
        }

        public void Disp()
        {
            for (int i = 0; i < size; i++)
            {
                Console.WriteLine("Record Number {0}",i);
                Console.WriteLine(e[i]);
            }
        }
    }

    class Main_Class
    {
        public static void Main()
        {
            while (true)
            {
                Console.WriteLine("Menu");
                Console.WriteLine("1.Add 2.Display 3.Exit");
                Console.WriteLine("Choice:");
                int c = Int32.Parse(Console.ReadLine());

                switch (c)
                {
                    case 1:
                        Employee_List el = new Employee_List();
                        el.AddFunc();
                        break;

                    case 2:
                        Employee_List e2 = new Employee_List();
                        e2.Disp();
                        break;

                    case 3:
                        return;
                }

            }
        }
    }
    
}



It gives me an error that indexers cannot have void types.I know that I am violating the meaning of the get property which is a construct that must return a value.
Thank you
Was This Post Helpful? 0
  • +
  • -

#8 Michael26   User is offline

  • Futurama: Insert funny joke here
  • member icon

Reputation: 414
  • View blog
  • Posts: 1,664
  • Joined: 08-April 09

Re: Employee Details using C sharp

Posted 25 August 2012 - 04:07 AM

This needs to return something, don't use Console.WriteLine()

public void this[int pos]
        {
            get
            {
                Console.WriteLine("{0} {1} {2} {3}",edept[pos],ename[pos],eno[pos],esal[pos]);              
            }
        }


Here is an example of an indexer
// Declare an array to store the data elements. 
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code 
    // to use [] notation on the class instance itself. 
    // (See line 2 of code in Main below.)         
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets 
            // the corresponding element from the internal array. 
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }

This post has been edited by Michael26: 25 August 2012 - 04:08 AM

Was This Post Helpful? 1
  • +
  • -

#9 rnty   User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 283
  • Joined: 14-August 12

Re: Employee Details using C sharp

Posted 25 August 2012 - 07:45 AM

Using an indexer to manipulate a single value is simple.I am trying to handle more than one value here.
Thank You
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7139
  • View blog
  • Posts: 24,247
  • Joined: 05-May 12

Re: Employee Details using C sharp

Posted 25 August 2012 - 10:52 AM

You are applying the indexer to the wrong class. Indexers are normally applied to classes that are meant to exhibit container like behavior.

A quick aside. You say that you've been programming in C, C++, and Java. I'd hoped that you picked up enough experience in those languages to know that using and running parallel arrays is usually a bad idea and a code smell that indicates you need to use a class or structure to keep the pieces together.

Here is an example that is like your code above in post #1, but demonstrates the incorrect application of an indexer leading to logical errors as you read the code. The code will run, but it just doesn't make sense to a normal reader. It's causes a lot of WTF!?!? moments:
using System;
using System.Collections.Generic;
using System.Text;

namespace BadIndexer
{
class Person
{
    struct Info
    {
        public string first;
        public string last;
    }

    List<Info> names = new List<Info>();

    public void AddPerson(string first, string last)
    {
        Info info = new Info();
        info.first = first;
        info.last = last;
        names.Add(info);
    }

    public int Count { get { return names.Count; } }

    public object this[int i]
    {
        get 
        {
            // Use anonymous objects to get the effect rnty wants
            return new { 
                            First = names[i].first, 
                            Last = names[i].last 
                        }; 
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();

        // Why am I adding a person to a person? Multiple personality disorder?
        person.AddPerson("Sybil", "Dorsett");
        person.AddPerson("Victoria", "Scharleau");
        person.AddPerson("Peggy Lou", "Baldwin");
        person.AddPerson("Mary", "Dorsett");

        // We are getting back an anonymous object, we use dynamic so that
        // the compiler doesn't complain about using properties it doesn't
        // know about yet.
        for (int i = 0; i < person.Count; i++)
        {
            dynamic identity = person[i];
            Console.WriteLine("person {2}: {0} {1}", identity.First, identity.Last, i);
        }

        // And we can't change any of the values. The following will give
        // a runtime exception:
        //     dynamic sybil = person[0];
        //     sybil.First = "Marcia";
    }
}
}



This code, on the other hand, shows the container behavior and makes more sense.
using System;
using System.Collections.Generic;
using System.Text;

namespace GoodIndexer
{
class Personality
{
    public string First { get; set; }
    public string Last { get; set; }
}

class Person
{
    List<Personality> personalities = new List<Personality>();

    public void AddPersonality(string first, string last)
    {
        personalities.Add(new Personality() { First = first, Last = last });
    }

    public int Count { get { return personalities.Count; } }

    public Personality this[int i]
    {
        get { return personalities[i]; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();

        person.AddPersonality("Sybil", "Dorsett");
        person.AddPersonality("Victoria", "Scharleau");
        person.AddPersonality("Peggy Lou", "Baldwin");
        person.AddPersonality("Mary", "Dorsett");

        for (int i = 0; i < person.Count; i++)
        {
            Personality identity = person[i];
            Console.WriteLine("person {2}: {0} {1}", identity.First, identity.Last, i);
        }

        // And now we can change the name
        Personality sybil = person[0];
        sybil.First = "Marcia";

        Personality marcia = person[0];
        Console.WriteLine("person 0: {0} {1}", marcia.First, marcia.Last);
    }
}
}


This post has been edited by Skydiver: 25 August 2012 - 10:55 AM

Was This Post Helpful? 0
  • +
  • -

#11 rnty   User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 283
  • Joined: 14-August 12

Re: Employee Details using C sharp

Posted 27 August 2012 - 10:08 AM

I coded something like this
class Program
    {
        static void Main(string[] args)
        {
            int ch,ch2;
            string nam;
            EmployeeList elist = new EmployeeList();
            Employee emp;
            while (true)
            {
                Console.WriteLine("1)Add employee 2)Search by code 3)search by name4)exit ");
                Console.WriteLine("Enter choice ");
               ch=Convert.ToInt32(Console.ReadLine());
                switch(ch)
                {
                    case 1:
                        emp = new Employee();
                        emp.Accept();
                        elist.Add(emp);
                        break;
                    case 2:
                        Console.WriteLine("enter search Code : ");
                        ch2 = Convert.ToInt32(Console.ReadLine());
                        emp = elist[ch2];
                        if (emp != null)
                            emp.Show();
                        else Console.WriteLine("not found");

                        break;
                    case 3:
                        Console.WriteLine("enter search name : ");
                       nam = Console.ReadLine();
                        emp = elist[nam];
                        if (emp != null)
                            emp.Show();
                        else Console.WriteLine("not found");

                        break;
                    case 4:
                        goto exit;
                        break;
                    default :
                        Console.WriteLine("Invalid choice");
                        break;

                }
                Console.ReadLine();
            }
        exit:
            Console.ReadLine();
        }
    }
    class Employee
    {
        int code;
        string name, dept;
        public int Code
        {
            get { return code; }
        }
        public string Name
        {
            get { return name; }
        }
        public void Accept()
        {
            Console.WriteLine("Name : ");
            name = Console.ReadLine();
            Console.WriteLine("Code : ");
            code = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Dept : ");
            dept = Console.ReadLine();
        }
        public void Show()
        {
            Console.WriteLine("Name : "+name+" Code : "+code+" Dept : "+dept);
        }
    }
    class EmployeeList
    {
        Employee[] list = new Employee[3];
        int size;
        public void Add(Employee e)
        {
            if (size >= list.Length)
                throw new IndexOutOfRangeException("list is full");
            list[size] = e;
            size++;
        }
        public Employee this[int searchCode]
        {
            get
            {
                if (size == 0)
                    throw new Exception("list empty!");
                for (int i = 0; i < size; i++)
                {
                    if (list[i].Code == searchCode)
                        return list[i];
                }
                return null;
            }
        }
        public Employee this[string searchName]
        {
            get
            {
                if (size == 0)
                    throw new Exception("list empty!");
                for (int i = 0; i < size; i++)
                {
                    if (list[i].Name == searchName)
                        return list[i];
                }
                return null;
            }
        }
    }
}




Thank you all for your inputs.Grateful.
Was This Post Helpful? 0
  • +
  • -

#12 Michael26   User is offline

  • Futurama: Insert funny joke here
  • member icon

Reputation: 414
  • View blog
  • Posts: 1,664
  • Joined: 08-April 09

Re: Employee Details using C sharp

Posted 27 August 2012 - 12:15 PM

Just curious, in your employee list why you only have 3?
You only supposed to have 3 employees?
And please review the Generics

This post has been edited by Michael26: 27 August 2012 - 12:15 PM

Was This Post Helpful? 0
  • +
  • -

#13 rnty   User is offline

  • D.I.C Regular

Reputation: 19
  • View blog
  • Posts: 283
  • Joined: 14-August 12

Re: Employee Details using C sharp

Posted 28 August 2012 - 08:49 AM

This is just a test program for indexers.No specific reason for the size 3.Thanks for the link.

This post has been edited by rnty: 28 August 2012 - 08:55 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1