Delegates vs. Function Pointers, part 3: C# 1.0

This is part 3 in a series about state and function pointers; part 1 is here.

Last time, we saw that it is impossible to bundle context along with a function pointer in C.

In C#, it is possible to fully achieve my standard example.  In order to explain how this works behind the scenes, I will limit this post to C# 1.0 and not use a lambda expression.  This also means no LINQ, generics, or extension methods, so I will, once again, need to write the filter method myself.

delegate bool IntFilter(int num);

static ArrayList Filter(IEnumerable source, IntFilter filter) {
    ArrayList retVal = new ArrayList();

    foreach(int i in source)
        if (filter(i))
            retVal.Add(i);
            
    return retVal;
}

class GreaterThan {
    public GreaterThan(int b) {
        this.bound = b;
    }
    int bound;
    public bool Passes(int num) {
        return num > bound;
    }
}

int x = 2;
int[] numbers = { 1, 2, 3, 4 };
Filter(numbers, new IntFilter(new GreaterThan(x).Passes));

Please excuse the ugly code; in order to be true to C# 1.0, I can’t just write an iterator, and I can’t implicitly create the delegate.

This code creates a class called GreaterThan that holds the Passes method and the state used by the method.  I create a delegate to pass to Filter out of the Passes method for an instance of the GreaterThan class from the local variable.

To understand how this works, we need to delve further into delegates.  .Net delegates are more than just type-safe function pointers. Unlike the function pointers we've looked at, delegates include state – the Target property. This property stores the object to pass as the hidden this parameter to the method (It's actually somewhat more complicated than that; I will describe open and closed delegates at a later date).  My example creates a delegate instance in which the Target property points to the GreaterThan instance.  When I call the delegate, the Passes method is called on the correct instance from the Target property, so it can read the bound field.

Next time, we'll see how the C# 2.0+ compilers generate all this boilerplate for you using anonymous methods and lambda expressions.

37 comments:

This curiosity you describe is fantastic Rita

The above article is nice and interesting, thank you willing to share! Greetings success of admin Percetakan Murah Rawamangun Jakarta Timur wish you deign to visit my website, thank you :)

I advise you to check https://writemyessay4me.org/blog/computer-science-career out if you want to know more about computer science career. It will help you to achieve success

Thanks for the best share and i loved it,
cinema hd for windows10

Delegates vs. Function Pointers, part 3, is really great and valuable article for all the new users to developing their high interest in that but there are also some very great opportunities available like the most beneficial essay writing services which is very essential in giving their best and desirable writing services in cheap rates.

Nice post. You work very well. We provide custom boxes at wholesale rate. You can visit our site and get more information.
Custom Hair Extension Boxes Packaging UK

Beds Online: Buy Beds Online in india at best price. Shop from Customhouzz the best bed offering a wide range of king size bed, queen size bed, double bed, single bed and many more collection.

Buy Sharara Suits online for women. Parchhai is offering latest design sharara suits online in India for ladies/women, our product are perfect combination of quality price, what are you waiting for shop with us today and grab the exciting deals on your favourite design suits.

great work. I would love to know more about that. Meanwhile android has made entertainement much easy like you can watch movies and tv shows anytime and anywhere on cinema hd apk. you can easily download cinema hd apk on any device. Even firestick supports cinema hd how to install cinema hd apk on firestick.
download cinema apk is probably the best movie app for android users.

Thanks for the best share and i loved it, 192.168.o.1

These things they still say on social networks yo whatsapp of https://yowaplus.net

Players contact the display screen to open a package deal and acquire a bonus payout. They could hold touching packages for extra bonuses till one package deal lastly reveals a "pooper," which ends the spherical. These bonus rounds helped video slots grow in popularity, but they don't seem to be} as prevalent right now, as recreation designers experiment with format. A generous welcome bonus is a should 온라인 카지노 for any respected online casino.

Great blog
Greeceassignmenthelp.com is a leading provider of online assignment help in Greece, catering to the needs of students from different academic backgrounds. Writers can provide you with customized solutions that meet your specific academic requirements.

Thanks for your beautiful content. I am enjoyed to read this information and learned a lot. Thank you so much for your good content.
proceso de divorcio de nueva jersey

A commotion was recently sparked by the disclosure of a Jetblue name change policy. The airline is implementing this adjustment as part of its effort to prioritise its consumers. They will be able to better communicate the company's principles and goals with this new name, and it will also be simpler for customers to discover them online. The airline is certain that the new logo will grow its client base and market share.

Turkish Airlines Panama Office: Improving Latin American Travel Experiences
Turkish Airlines, one of the top airlines in the world, is well known for its outstanding customer care, cutting-edge fleet, and large global network. The airline, which has a long history spanning more than 87 years, has constantly increased its reach to accommodate passengers from all over the world.

People mostly ask Where Does Emirates Fly in the US ? Emirates' hub is in Dubai, from whence it serves 161 destinations in 85 countries on six continents. In June 2004, Emirates launched non-stop passenger service from Dubai to New York JFK. Since then, it has expanded to Houston, Los Angeles, San Francisco, Dallas/Fort Worth, Seattle, Washington, DC, Boston, Chicago, Orlando, Newark, and Miami. Additionally, it flies to over 96 different destinations each week.

Modern amenities and facilities are available at the Modern amenities and facilities are available at theAvianca Airlines Miami Office to improve travellers' journeys. Modern technology is available at the airline's check-in desks, allowing for quick and effective check-in procedures. Additionally, passengers may take advantage of cosy seating areas and free Wi-Fi to keep connected as they wait for their flights. to improve travellers' journeys. Modern technology is available at the airline's check-in desks, allowing for quick and effective check-in procedures. Additionally, passengers may take advantage of cosy seating areas and free Wi-Fi to keep connected as they wait for their flights.

El al cancel flight can still happen, though, for a number of reasons. Travellers must be aware of their rights under El Al's cancellation policy, as well as their choices for obtaining compensation. Passengers may reduce the inconvenience brought on by flight cancellations and look forward to a suitable resolution offered by the airline by being informed of their rights and taking the necessary actions.

A hydraulic filter cart is a portable filtration system designed for maintaining the cleanliness of hydraulic fluids. It typically consists of a pump, motor, filter housing, hoses, and wheels for easy mobility. The filter cart is used to remove contaminants such as dirt, particles, and water from hydraulic fluids, ensuring optimal performance and extending the life of hydraulic systems and components.

AirlinesOffice is a comprehensive online platform that offers detailed information about Southwest Airlines Detroit Metropolitan Wayne County Airport Terminal (DTW)
. This specific terminal, located at Detroit Metropolitan Wayne County Airport in Michigan, serves as a key point of contact for passengers seeking assistance or information regarding Southwest Airlines' flights, services, and amenities at DTW. AirlinesOffice provides a user-friendly interface where travelers can find up-to-date details about the Southwest Airlines Detroit Metropolitan Wayne County Airport Terminal, including terminal facilities, check-in procedures, baggage services, and other relevant information. With the help of AirlinesOffice, passengers can navigate their journey through DTW smoothly, whether it's checking flight status, locating services, or obtaining general airport information related to Southwest Airlines.

Hlo Selena Gomeezz here, working for a travel agency. I've been there three years and know a lot about flights and airlines. I have a lot of information on Kuwait Airways New York office headquarters, so please visit my page and I hope I can help you.



Thank you for sharing. Marknjohson is an email support professional with expertise in AOL IMAP settings. He has in-depth knowledge of configuring email clients and troubleshooting common issues related to AOL email accounts. He is skilled in providing technical support to clients with an ability to effectively communicate complex technical solutions in simple terms.

We take pride in offering each traveller individualised help at the Garuda Airlines New York Office making sure that your journey starts smoothly and without effort. Our devoted staff of experts is knowledgeable with the complexities of foreign travel and is ready to help you with all of your flight questions, booking needs, and travel preparation.

Immerse yourself in a world of flavor with Kangvape Flavors 3000. This cutting-edge vaping device boasts an impressive selection of 3000 puffs worth of delectable e-liquid flavors. From classic blends to exotic concoctions, Kangvape Flavors 3000 offers an extended and satisfying vaping experience.

A salwar suit is a traditional ensemble worn by women of all ages and communities in India. A salwar suit mainly consists of a tunic, a pair of trousers and a dupatta. This suit is the best option to feel comfortable during more movements. Today, women wear different varieties of salwar kameez that are a blend of traditional and contemporary styles.

Order lowest price multiple sclerosis medicine from india visit denopsy 7mg teriflunomide tablet

Stuck on outlook stuck on loading profile'? Fret not; you are in the right place. Hello, I'm your Outlook loading issue troubleshooter. My name is Liam, and let me take the frustration away. With my expertise, I can troubleshoot this snag, ensuring your Outlook runs smoothly. Connect with me or my tech support team 24/7 for immediate solutions.

lot polish airlines change flight
Regarding flight change fees, LOT Polish Airlines has precise rules, although these can change over time. For changing flights, LOT Polish Airlines typically imposed a fee; the precise sum depended on the price class, the route, and how close to the departure date the change was made.

Fellow travelers! If you're arriving at San Francisco International Airport (SFO) with Frontier Airlines, you'll be pleased to know that your journey concludes at the Frontier Arrival Terminal SFO. It's not just an endpoint; it's a place where your adventures find closure with a touch of convenience and warmth.

When cases proceed to court, traffic lawyers represent their clients, presenting arguments, cross-examining witnesses, and advocating for their rights before a judge or jury. Traffic Lawyer Henrico VA

Post a Comment