C# How to call method from another class - c#

I'm beginner with C# I need little help how to call method from one Class to another class. Since C# is strongly typed language I found it difficult to navigate through classes, methods etc.
I want to take 'GetSalesRevenue() - Class Salesman' and use it at departments 'GetRevenue() - Class Departments ';
This is my first attempt with C# OOP. Any help is appreciated!
using System;
using System.Collections.Generic;
using System.Text;
namespace EmployeeDepartment
{
class Departments
{
public Departments(string[] developers, string[] salesman)
{
Developers = developers;
Salesman = salesman;
}
public string[] Developers { get; set; }
public string[] Salesman { get; set; }
public void GetRevenue(Salesman value)
{
Console.WriteLine("Sum of revenus from All salesmen");
}
public void GetSkillset()
{
Console.WriteLine("Print all skills from the developers in the deparment");
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace EmployeeDepartment
{
class Salesman : Employee
{
public Salesman(string name, string surname, int age, int salary, int salesrevenue, int salarysalesman) : base(name, surname, age, salary)
{
SalesRevenue = salesrevenue;
SalarySalesman = salarysalesman;
}
private double SalesRevenue { get; set; }
public double SalarySalesman { get; set; } = 400;
// Salary is default 400 and Role is default Sales
public double AddRevenue(double addRevenue)
{
return SalesRevenue += addRevenue;
}
public double GetSalesRevenue()
{
return SalesRevenue;
}
public double GetSalary(double plus)
{
return (SalesRevenue / 10) * 100;
}
}
}

I guess you're looking for something like this:
class Departments
{
public Departments(string[] developers, string[] salesman)
{
Developers = developers;
Salesman = salesman;
}
public string[] Developers { get; set; }
public string[] Salesman { get; set; }
public void GetRevenue(Salesman salesman)
{
double revenue = salesman.GetSalesRevenue();
Console.WriteLine($"Sum of revenus from All salesmen: {revenue}" );
}
public void GetSkillset()
{
Console.WriteLine("Print all skills from the developers in the deparment");
}
}

Related

Error CS1955: Non-invocable member 'ShoppingCartItem.GetTotal' cannot be used like a method

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CKK.Logic.Models
{
public class ShoppingCartItem
{
private Product product;
private int quantity;
public ShoppingCartItem(Product aProduct, int aQuantity)
{
product = aProduct;
quantity = aQuantity;
}
public Product GetProduct()
{
return product;
}
public void SetProduct(Product value)
{
product = value;
}
public int GetQuantity()
{
return quantity;
}
public void SetQuantity(int value)
{
quantity = value;
}
public decimal GetTotal { get; }
}
}
Error CS1955 Non-invocable member ShoppingCartItem.GetTotal cannot be used like a method.
This is the error I'm getting and I can't seem to get around this error I would greatly appreciate any help
At some point in the code you haven't shown, you're trying to access the GetTotal property as if it were a method.
decimal total = item.GetTotal(); // Will not work
To access a property, omit the parentheses:
decimal total = item.GetTotal;
However, GetTotal is a poor choice of name for a property. I would suggest calling it Total instead.
Looking at your other methods, I'm guessing you're from a Java background? In C#, you would usually use properties instead of pairs of Get.../Set... methods:
public class ShoppingCartItem
{
public ShoppingCartItem(Product product, int quantity)
{
Product = product;
Quantity = quantity;
}
public Product Product { get; set; }
public int Quantity { get; set; }
public decimal Total { get; }
}
Properties - C# Programming Guide | Microsoft Docs
When declaring getters and setters like this public decimal GetTotal { get; } in C# you are declaring a property, and not a method. So in this case you GetTotal is a property from which you can get the value like thisShoppingCartItem.GetTotal. As far as I can tell, GetTotal should not be a field but a method calculating the total.
I would rewrite your code like this:
public class ShoppingCartItem {
private Product product {public get; public set; } //is it nessecary to have both public?
private int quantity {public get; public set; }
public ShoppingCartItem(Product aProduct, int aQuantity)
{
product = aProduct;
quantity = aQuantity;
}
public decimal GetTotal {
return product.price * quantity;
}
}

How inheritance variables from another class?

I don't know how to inheritance a variables from another class. I write code in C# and I created two classes
First one is Osoba (engl. Person) which has variables ime, prezime, OIB (engl. name, last name, ID) and I have another class Racun (engl. account) which means bank account.
Class Racun has variables podaci o vlasniku računa (engl. account holder information), broj računa (engl. serial number of account) and stanje računa (engl. bank account balance).
Well podaci o vlasniku računa (engl. account holder information) needs to have variables from class Osoba. How can I do that?
I will show you my two created classes with code. If you notice both classes need to have 3 variables, I didn't create first variable in class Racun (engl. account) because the first one need to contain variables from class Osoba (engl. Person).
Osoba.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Osoba
{
public string ime { get; set; }
public string prezime { get; set; }
public int oib { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.ime = tempIme;
this.prezime = tempPrezime;
this.oib = tempOib;
}
}
}
Racun.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Racun
{
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(int tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
this.brojRacuna = tempbrojRacuna;
this.stanjeRacuna = tempstanjeRacuna;
}
}
}
If your povr variable needs to hold the same pieces of information as in Osoba, you can either have povr be a reference to an instance of Osoba:
class Racun
{
public Osoba povr { get; set; }
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(Osoba tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
//etc
Or you could make a struct to hold common information:
namespace Vjezba6_1
{
struct PodaciOVlasnikuRacuna //i'm sure you can shorten this, but i don't know the language
{
public string ime;
public string prezime;
//other account holder information
}
}
And use this in your classes, like so:
namespace Vjezba6_1
{
class Osoba
{
public PodaciOVlasnikuRacuna podaci { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.podaci.ime = tempIme;
this.podaci.prezime = tempPrezime;
this.podaci.oib = tempOib;
}
}
}
namespace Vjezba6_1_v2
{
class Osoba
{
public Podaci povr { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.povr.ime = tempIme;
this.povr.prezime = tempPrezime;
this.povr.oib = tempOib;
}
}
}

Access the data in the dictionary when the item is an object?

So I am lost on how to send data back to the object once it is added to the dictionary.
With this data structure that I made http://pastebin.com/HicZMzAt for full code
I have
public class Computer
{
public Computer() { }
public Computer(int _year)
{
dropOffDate = DateTime.Now;
RepairFinished = false;
Year = _year;
}
private DateTime dropOffDate;
public bool RepairFinished;
private readonly int Year;
public static string Plate;
private string make;
public string Make
{
get { return make; }
set { make = value; }
}
public string Model { get; set; }
public string ComputerTicketId { get; set; }
public bool IsLaptop { get; set; }
public Location Location { get; set; }
public int HoursWorked { get; set; }
public double PartsCost { get; set; }
public DateTime DateFinished { get; set; }
// public virtual double TotalCost { get { TotalCost = (this.HoursWorked * 50) + PartsCost; } set; }
public void ComputerPickUp()
{
Console.WriteLine("Cost is {0:C} ", this.HoursWorked);
RepairFinished = true;
}
where I want to calculate the different cost for repairs for each dropped of system.
public class Laptop : Computer
{
public bool HasCharger { get; set; }
public Laptop(int year, bool _HasCharger)
: base(year)
{
HasCharger = _HasCharger;
}
//TODO overide for COST ! + 10
and I have a desktop class also were the cost of repair is cheaper for Desktop systems.
But I am using
public static class Repair
{
public static Dictionary<string, object> RepairLog { get; set; }
}
to track the repairs
and now I am lost in the UI part of the program to get the data to figure out the pricing.
public class RepairUI
{
....edited
Repair.RepairLog = new Dictionary<string, object>();
....
Computer = new Desktop(ComputerYear, HasLcd);
And that is how I am lost about the way to handle the data , the class data for each repair unit (desktop / NBK ) is organized in the dictionary and now I want to get the data and edit the repair cost of the object , but I can't seem to figure out how to reach the object.
So how could I ask upon pick up hours worked and calculate the info for the unit ?
This sounds like a great moment to use an Interface!
public Interface IRepairable
{
double GetRepairCost();
}
Then redefine Computer
public class Computer : IRepairable
{
public double GetRepairCost()
{
return (this.HoursWorked * 50) + PartsCost;
}
}
and Laptop
public class Laptop : Computer
{
public new double GetRepairCost()
{
return base.GetRepairCost() + 10;
}
}
and Repair
public static class Repair
{
public static Dictionary<string, IRepairable> RepairLog { get; set; }
}
And now you have a dictionary of things that you can call GetRepairCost() on! These could be Computers or Laptops or a mix, it doesn't matter to the RepairLog!

How can I query different tables dynamically with LINQ?

So I'm not sure if you can do this or not, but I would like to avoid using SQL strings if I can. What I would like to do with Linq/DbContexts is the following that can be done easily with SQL:
string sql = "UPDATE " + tableName + " SET Status=0 WHERE Id=" + formId.ToString();
I can easily put this into a loop where tableName and formId are given dynamically and execute no problem.
I have multiple DbContexts, so I don't know of any way to do something like:
var db = new *dynamicallyChosenContext*()
var query = from p in db.*dynamicallyChosenAlso*
where p.Id == formId
select p;
foreach (var result in query)
{
result.Status = 0;
}
db.SaveChanges()
Thanks for the help!
Here is a piece of working code that can update different tables at runtime from different contexts without using reflection.
namespace DemoContexts
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
public interface IThing
{
int Id { get; set; }
int Status { get; set; }
}
public class FirstPersonThing : IThing
{
[System.ComponentModel.DataAnnotations.Key]
public int Id { get; set; }
public int Status { get; set; }
public string Foo { get; set; }
}
public class SecondPersonThing : IThing
{
[System.ComponentModel.DataAnnotations.Key]
public int Id { get; set; }
public int Status { get; set; }
public string Bar { get; set; }
}
public class FirstContext : DbContext
{
public FirstContext() : base("FirstContext") { }
public DbSet<FirstPersonThing> MyThings { get; set; }
public DbSet<SecondPersonThing> YourThings { get; set; }
}
public class SecondContext : DbContext
{
public SecondContext() : base("SecondContext") { }
public DbSet<FirstPersonThing> MyThings { get; set; }
public DbSet<SecondPersonThing> YourThings { get; set; }
}
class Program
{
static void Main(string[] args)
{
int contextType = 1;
int thingType = 1;
DbContext db = RunTimeCreatedContext(contextType);
IQueryable<IThing> collection = RunTimeCreatedCollection(db, thingType);
UpdateRuntimeDeterminedThings(db, collection, 1);
Console.ReadLine();
}
public static void UpdateRuntimeDeterminedThings(DbContext db,
IQueryable<IThing> collection,
int formId)
{
var querySet = collection.Where(p => p.Id == formId).ToList();
foreach (var result in querySet)
{
result.Status = 0;
}
db.SaveChanges();
}
static DbContext RunTimeCreatedContext(int contextType)
{
if (contextType == 0)
{
return new FirstContext();
}
else
{
return new SecondContext();
}
}
static IQueryable<IThing> RunTimeCreatedCollection(DbContext db, int thingType)
{
if (thingType == 0)
{
return db.Set(typeof(FirstPersonThing)) as IQueryable<IThing>;
}
else
{
return db.Set<SecondPersonThing>();
}
}
}
}
The first thing to note is that all this is statically typed so to perform a generic query against different types of objects these objects must have common property signatures and this conceptually is expressed in the IThing interface.
A second thing to note is how the IQueryable is generated. It is generated by the DbContext.Set Method (Type) in the first instance (for the FirstPersonThings), it is generated by the DbContext.Set<TEntity> Method in the second instance. The first uses a type determined at runtime and requires a cast (but could be useful to use passing types at runtime), the second uses generics and the types are determined at compile time. There are obviously a number of other ways that this function could work.
Finally the method UpdateRuntimeDeterminedThings works because it uses properties and methods that are shared across the types (either with base types/inheritance or by the implementation of interfaces).
None of this is actually dynamic programming (which is possible using the dynamic type) and I have used the term runtime determined rather than dynamic to describe how this works.
There is a technique in functional programming, called Currying, where you could pass as much parameters as you want, so you are able to access them.
Here is an exemple: http://blogs.msdn.com/b/sriram/archive/2005/08/07/448722.aspx
P.S: You could use a currying function to iterate through yours DBContexts.
I think you have to use reflection if you want to use 'code' and not sql strings. That's just how C# works... This is how you could do it:
using System;
using System.Data.Entity;
using System.Linq;
public class TestContext : DbContext
{
public DbSet<Box> Boxes { get; set; }
public DbSet<Thing> Things { get; set; }
}
public abstract class Base
{
public int Id { get; set; }
}
public class Box : Base
{
public string Title { get; set; }
}
public class Thing : Base
{
public string Name { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
var db = new TestContext();
DoIt(GetPropValue(db, "Boxes") as IQueryable<Base>);
DoIt(GetPropValue(db, "Things") as IQueryable<Base>);
}
private static void DoIt(IQueryable<Base> b)
{
Console.WriteLine(
b.Single(t => t.Id == 1).Id);
}
private static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
}
Obviously you can then put the strings in a list etc, whatever you need.

How to bind an advBandedGridView at run time?

I am new in the using of DevExpress. I need to design and bind a complex DataGrid.
I have designed it using the Designer. The datagrid is of type Master-Detail, and it contains the 'MainGrid' and other detail grids. One of them is of type: 'advBandedGridView'
The design of the MainGrid is as shown below:
And the design of the 'advBandedGridView' is as follows:
Now, I need to fill my DataGrid using Lists collections, so I used the following Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
ArrayList a = new ArrayList();
Term_Space_Grid t = new Term_Space_Grid("x", "y", true, "z");
t.expansions = new List<MyExpansions>();
t.expansions.Add(new MyExpansions(0, "Aya", 0, 0, 0, 0, 0));
a.Add(t);
resultsGridControl.DataSource = a;
}
}
public class Term_Space_Grid
{
public string x { get; set; }
public string y { get; set; }
public string g { get; set; }
public bool z { get; set; }
public List<MyExpansions> expansions { get; set; }
public Term_Space_Grid(string x, string y, bool z, string g)
{
this.x = x;
this.y = y;
this.z = z;
this.g = g;
}
}
public class MyExpansions
{
public Morphos morphos { get; set; }
public Semantics semantics { get; set; }
public MyExpansions(int morphoID, string morphoDerivation, int synID, int subID, int supID, int hasID, int insID)
{
this.morphos = new Morphos(morphoID, morphoDerivation);
this.semantics = new Semantics(synID, subID, supID, hasID, insID);
}
}
public class Morphos
{
//public List<Morph> morph{ get; set; }
public Morph morph { get; set; }
public Morphos(int morphoID, string morphoDerivation)
{
//this.morph = new List<Morph>();
//this.morph.Add(new Morph(morphoID, morphoDerivation));
this.morph = new Morph(morphoID, morphoDerivation);
}
}
public class Semantics
{
public List<Sem> synonyms { get; set; }
public List<Sem> subClasses { get; set; }
public List<Sem> superClasses { get; set; }
public List<Sem> hasInstances { get; set; }
public List<Sem> instanceOf { get; set; }
public Semantics(int id1,int id2, int id3, int id4, int id5 )
{
this.synonyms = new List<Sem>();
this.subClasses = new List<Sem>();
this.superClasses = new List<Sem>();
this.hasInstances = new List<Sem>();
this.instanceOf = new List<Sem>();
this.synonyms.Add(new Sem(id1));
this.subClasses.Add(new Sem(id2));
this.superClasses.Add(new Sem(id3));
this.hasInstances.Add(new Sem(id4));
this.instanceOf.Add(new Sem(id5));
}
}
public class Morph
{
public int MorphoID { get; set; }
public string MorphoDerivation { get; set; }
public Morph(int morphoID, string morphoDerivation)
{
this.MorphoID = morphoID;
this.MorphoDerivation = morphoDerivation;
}
}
public class Sem
{
public int SemID { get; set; }
//public string MorphoDerivation { get; set; }
public Sem(int semID)
{
this.SemID = semID;
}
}
}
However, I found that the result is built as a new DataGrid that has not any designed form. I mean that the detail tabs that I define in the Designer are not appeared in the resulted grid.
The result is as follows:
Notes
The design of the resulted grid which is totally different from my design, I think it is just like the Lists objects.
The other problem which is the appearance of :
"WindowsFormsApplication2.Morphos" and "WindowsFormsApplication2.Semantics" at the cells of the grid rather than the values that I passed!
Firstly, you should create associations between your data object properties and GridView columns via GridColumn.FildName property.
For your main view (gridView2) it looks like this:
// gridColumn1
this.gridColumn1.Caption = "ID";
this.gridColumn1.FieldName = "x"; // associate this column with Term_Space_Grid.x property
this.gridColumn1.Name = "gridColumn1";
Please read the following article for more details: Creating Columns and Binding Them to Data Fields
Secondly, you can not directly bind columns to object's nested properties (for example to MyExpansions.semantics.subclasses.SemID).
To bypass this restriction you can use several approaches:
The simplest approach is using Unbound Columns and the corresponding ColumnView.CustomUnboundColumnData event (you can handle this event to provide data from nested objects).
You can also use the approach demonstrated in the following KB article: How to display and edit complex data properties in grid columns
Thirdly, to get official and guaranteed answer you should address any urgent question related to any DevExpress products directly to DevExpress Support Center.

Categories

Resources